<?php
include "auth.php";
checkPermission(['admin','manager','staff']); // allow all roles here
?>
<?php

require_once "db.php";

// -------------------------
// Handle Supplier Create
// -------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'create') {
        $name = trim($_POST['supplier_name']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        if ($name !== '') {
            $stmt = $conn->prepare("INSERT INTO suppliers (supplier_name, phone, address) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $name, $phone, $address);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: suppliers.php");
        exit();
    }
    if ($_POST['action'] === 'edit') {
        $id = intval($_POST['supplier_id']);
        $name = trim($_POST['supplier_name']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE suppliers SET supplier_name=?, phone=?, address=? WHERE supplier_id=?");
            $stmt->bind_param("sssi", $name, $phone, $address, $id);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: suppliers.php");
        exit();
    }
}

// -------------------------
// Handle Delete
// -------------------------


$message = "";
$message_type = ""; // success or error

if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        // Check if supplier has any purchase records
        $check = $conn->prepare("SELECT COUNT(*) AS total FROM purchases WHERE supplier_id = ?");
        $check->bind_param("i", $id);
        $check->execute();
        $result = $check->get_result()->fetch_assoc();
        $check->close();

        if ($result['total'] > 0) {
            // Cannot delete — related purchase records exist
            $message = "❌ This supplier cannot be deleted because there are related purchase records.";
            $message_type = "error";
        } else {
            // Safe to delete
            $stmt = $conn->prepare("DELETE FROM suppliers WHERE supplier_id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();

            $message = "✅ Supplier deleted successfully.";
            $message_type = "success";
        }
    }
}



// -------------------------
// Search
// -------------------------
$search = isset($_GET['search']) ? trim($_GET['search']) : "";
$sql = "SELECT * FROM suppliers";
if ($search !== '') {
    $sql .= " WHERE supplier_name LIKE '%" . $conn->real_escape_string($search) . "%'";
}
$sql .= " ORDER BY supplier_name ASC";
$suppliers = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Suppliers List</title>
        <link rel="stylesheet" href="css/style.css">
        <style>
            .alert {
    padding: 12px 18px;
    border-radius: 6px;
    margin-bottom: 15px;
    font-weight: 500;
    text-align: center;
}
.alert.success {
    background-color: #d1fae5;
    color: #065f46;
    border: 1px solid #10b981;
}
.alert.error {
    background-color: #fee2e2;
    color: #991b1b;
    border: 1px solid #ef4444;
}
.filter-box a{
    display: block;
    width: 100%;
    background: #10b981;
    color: #fff;
    margin: 0;
    text-align: center;
    font-size: 17px;
    font-weight: 400;
    padding: 14px 15px;
    border-radius: 7px;
    border: none;
    cursor: pointer;
}

        </style>
    </head>

    <body class=" supplier-page">
        <!-- Global header start -->
        <?php
            include("global/header.php");
         ?>
        <!-- Global header end -->

            <!-- Main -->
            <main class="main">
                <header class="topbar">
                    <button class="hamburger" id="hamburger" aria-label="Toggle menu">☰</button>

                    <div style="margin-left:8px;font-weight:600">Dashboard <span class="topbar-menu-space"> > </span> Suppliers</div>
                    <!-- Global Notification start -->
            <?php include("global/notify.php"); ?>
            <!-- Global Notification end -->
                    <div class="profile">
                    <button class="profile-btn" id="profileBtn" aria-expanded="false">
                        <span>Welcome <?php echo $_SESSION['username']; ?></span>
                        <img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" />
                    </button>
                    <nav class="dropdown" id="profileDropdown">
                        <a href="profile.php">Profile Settings</a>
                        <a href="users.php">Users Settings</a>
                        <a href="logout.php">Logout</a>
                    </nav>
                </div>
                </header>
                <?php if (!empty($message)): ?>
    <div class="alert <?= $message_type ?>">
        <?= htmlspecialchars($message) ?>
    </div>
<?php endif; ?>

        <section class="content">
            <div class="container">
                <div class="">
                    <div class="group-box">
                        <form method="get" class="search-form filter-box">
                            <div class="form-group">
                                <input type="text" name="search" placeholder="Search supplier..." value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn search-btn">🔍︎ Search</button>
                            </div>
                            <div class="form-group">
                                <button class="btn" onclick="openCreateModal()">✚ Create Supplier</button>
                            </div>
                            <div class="form-group">
                                <a href="suppliers-print.php" target="_blank">Print</a>
                            </div>
                        </form>
                    </div>
                    
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Supplier Name</th>
                            <th>Phone</th>
                            <th>Address</th>
                            <th style="width: 200px; text-align: center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($suppliers && $suppliers->num_rows > 0): ?>
                        <?php while ($s = $suppliers->fetch_assoc()): ?>
                        <tr>
                            <td>
                                <?php echo $s['supplier_id']; ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($s['supplier_name']); ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($s['phone']); ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($s['address']); ?>
                            </td>
                            <td class="suppliers-action-btn">
                                <button class="btn" onclick='openEditModal(<?php echo json_encode($s); ?>)'>Edit</button>
                                <a href="?delete=<?php echo $s['supplier_id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this supplier?')">Delete</a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        <?php else: ?>
                        <tr>
                            <td colspan="5" style="text-align:center;color:#6b7280;">No suppliers found</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Create Modal -->
        <div class="modal" id="createModal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('createModal')">&times;</span>
                <h3>Create Supplier</h3>
                <form method="post">
                    <input type="hidden" name="action" value="create">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="supplier_name" placeholder="Full Name" required>
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" placeholder="+880">
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" name="address" placeholder="full address">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="submit-btn btn">Save</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Edit Modal -->
        <div class="modal" id="editModal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('editModal')">&times;</span>
                <h3>Edit Supplier</h3>
                <form method="post" id="editForm">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="supplier_id" id="editId">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="supplier_name" id="editName" required>
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" name="phone" id="editPhone">
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" name="address" id="editAddress">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn submit-btn">Update</button>
                    </div>
                </form>
            </div>
        </div>


        <script>
            // Sidebar accordion: click ONLY the top-level buttons, not the whole LI.
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault(); // keep as a toggle, no page jump
                    const currentItem = btn.parentElement; // .has-submenu
                    const isOpen = currentItem.classList.contains("open");

                    // Close other open menus (accordion behavior)
                    document.querySelectorAll(".has-submenu.open").forEach((li) => {
                        if (li !== currentItem) {
                            li.classList.remove("open");
                            const b = li.querySelector(".menu-link");
                            if (b) b.setAttribute("aria-expanded", "false");
                        }
                    });

                    // Toggle current
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });

            // Ensure clicks inside submenu DO NOT toggle/close the parent unintentionally
            document.querySelectorAll(".submenu").forEach((ul) => {
                ul.addEventListener("click", (e) => {
                    e.stopPropagation();
                });
            });

            // Mobile: show/hide sidebar
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => {
                sidebar.classList.toggle("active");
            });

            // Close sidebar when clicking outside on small screens
            document.addEventListener("click", (e) => {
                const isClickInside = sidebar.contains(e.target) || hamburger.contains(e.target);
                if (!isClickInside && sidebar.classList.contains("active")) {
                    sidebar.classList.remove("active");
                }
            });

            // Profile dropdown
            const profileBtn = document.getElementById("profileBtn");
            const profileDropdown = document.getElementById("profileDropdown");
            profileBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                const open = profileDropdown.classList.toggle("open");
                profileBtn.setAttribute("aria-expanded", String(open));
            });
            document.addEventListener("click", () => profileDropdown.classList.remove("open"));
        </script>

        <script>
            function openCreateModal() {
                document.getElementById('createModal').style.display = 'flex';
            }

            function openEditModal(supplier) {
                document.getElementById('editId').value = supplier.supplier_id;
                document.getElementById('editName').value = supplier.supplier_name;
                document.getElementById('editPhone').value = supplier.phone;
                document.getElementById('editAddress').value = supplier.address;
                document.getElementById('editModal').style.display = 'flex';
            }

            function closeModal(id) {
                document.getElementById(id).style.display = 'none';
            }
            window.onclick = function(event) {
                if (event.target.classList.contains('modal')) {
                    event.target.style.display = 'none';
                }
            }

            function printSuppliers() {
                const table = document.querySelector("table").outerHTML;
                const win = window.open("", "_blank", "height=700,width=900");
                win.document.write("<html><head><title>Suppliers</title></head><body>");
                win.document.write("<h2>Suppliers List</h2>");
                win.document.write(table);
                win.document.write("</body></html>");
                win.document.close();
                win.print();
            }
        </script>
        <script>
setTimeout(() => {
  const alert = document.querySelector('.alert');
  if (alert) alert.style.display = 'none';
}, 9000);
</script>


    </body>

</html>