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

require_once "db.php";

// -------------------------
// Handle Customer Create / Edit
// -------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // sanitize inputs
    $name = trim($_POST['customer_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');

    if ($_POST['action'] === 'create') {
        if ($name !== '') {
            $stmt = $conn->prepare("INSERT INTO customers (customer_name, customer_phone, customer_email, customer_address) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $name, $phone, $email, $address);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: customers.php");
        exit();
    }

    if ($_POST['action'] === 'edit') {
        $id = intval($_POST['customer_id'] ?? 0);
        if ($id > 0 && $name !== '') {
            $stmt = $conn->prepare("UPDATE customers SET customer_name=?, customer_phone=?, customer_email=?, customer_address=? WHERE customer_id=?");
            $stmt->bind_param("ssssi", $name, $phone, $email, $address, $id);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: customers.php");
        exit();
    }
}

// -------------------------
// Handle Delete
// -------------------------
$message = "";
$message_type = ""; // success or error

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

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

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



// -------------------------
// Search
// -------------------------
$search = isset($_GET['search']) ? trim($_GET['search']) : "";
$sql = "SELECT * FROM customers";
if ($search !== '') {
    $sql .= " WHERE customer_name LIKE '%" . $conn->real_escape_string($search) . "%'";
}
$sql .= " ORDER BY customer_name ASC";
$customers = $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>Customers List</title>
    <link rel="stylesheet" href="https://insaf.shopnofy.com/update9/css/style.css">
    <style>
        
        .modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);justify-content:center;align-items:center}
        .modal-content{background:#fff;padding:20px;border-radius:10px;width:420px;max-width:95%}
        .close{float:right;cursor:pointer;font-weight:bold}
        .suppliers-action-btn button, .suppliers-action-btn a { margin-right:6px; }
        .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="customer-page">
    <?php include("global/header.php"); ?>

    <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> Customers</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="filter-group">
                        <form method="get" class="search-form filter-box">
                            <div class="form-group">
                                <input type="text" name="search" placeholder="Search customer..." 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 Customer</button>
                    </div>
                    <div class="form-group">
                        <a href="customers-print.php" target="_blank">Print</a>
                    </div>
                        </form>
                    </div>

                    
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Customer Name</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Address</th>
                            <th style="width:200px;text-align:center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($customers && $customers->num_rows > 0): ?>
                            <?php while ($c = $customers->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo (int)$c['customer_id']; ?></td>
                                    <td><?php echo htmlspecialchars($c['customer_name']); ?></td>
                                    <td><?php echo htmlspecialchars($c['customer_phone']); ?></td>
                                    <td><?php echo htmlspecialchars($c['customer_email']); ?></td>
                                    <td><?php echo htmlspecialchars($c['customer_address']); ?></td>
                                    <td class="suppliers-action-btn" style="text-align:center;">
                                        <button class="btn" onclick='openEditModal(<?php echo json_encode($c, JSON_HEX_APOS|JSON_HEX_QUOT); ?>)'>Edit</button>
                                        <a href="?delete=<?php echo $c['customer_id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this customer?')">Delete</a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="6" style="text-align:center;color:#6b7280;">No customers found</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </main>

    <!-- Create Modal -->
    <div class="modal" id="createModal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('createModal')">&times;</span>
            <h3>Create Customer</h3>
            <form method="post">
                <input type="hidden" name="action" value="create">
                <label>Name</label><br>
                <input type="text" name="customer_name" placeholder="Full Name" required><br><br>

                <label>Phone</label><br>
                <input type="text" name="phone" placeholder="+880..."><br><br>

                <label>Email</label><br>
                <input type="text" name="email" placeholder="email@example.com"><br><br>

                <label>Address</label><br>
                <input type="text" name="address" placeholder="Full address"><br><br>

                <button type="submit" class="btn">Save</button>
            </form>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal" id="editModal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('editModal')">&times;</span>
            <h3>Edit Customer</h3>
            <form method="post" id="editForm">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="customer_id" id="editId">
                <label>Name</label><br>
                <input type="text" name="customer_name" id="editName" required><br><br>

                <label>Phone</label><br>
                <input type="text" name="phone" id="editPhone"><br><br>

                <label>Email</label><br>
                <input type="text" name="email" id="editEmail"><br><br>

                <label>Address</label><br>
                <input type="text" name="address" id="editAddress"><br><br>

                <button type="submit" class="btn">Update</button>
            </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>
    // Open/close modals
    function openCreateModal() {
        document.getElementById('createModal').style.display = 'flex';
    }
    function openEditModal(customer) {
        // customer is an object injected via json_encode
        document.getElementById('editId').value = customer.customer_id || '';
        document.getElementById('editName').value = customer.customer_name || '';
        document.getElementById('editPhone').value = customer.customer_phone || '';
        document.getElementById('editEmail').value = customer.customer_email || '';
        document.getElementById('editAddress').value = customer.customer_address || '';
        document.getElementById('editModal').style.display = 'flex';
    }
    function closeModal(id) {
        document.getElementById(id).style.display = 'none';
    }

    // Click outside to close
    window.onclick = function(event) {
        if (event.target.classList.contains('modal')) {
            event.target.style.display = 'none';
        }
    }


</script>
<script>
setTimeout(() => {
  const alert = document.querySelector('.alert');
  if (alert) alert.style.display = 'none';
}, 9000);
</script>
</body>
</html>
