<?php
/**
 * Admin - Manage Purchase Managers
 * Only accessible to admin users
 */

session_start();
include '../backend/config.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Get action
$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $status = isset($_POST['status']) ? $_POST['status'] : 'active';
    $manager_id = isset($_POST['manager_id']) ? $_POST['manager_id'] : '';
    
    if ($action === 'add') {
        // Validate
        if (empty($name) || empty($email) || empty($password)) {
            $error = 'Name, email, and password are required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email format';
        } else {
            // Hash password
            $hashed_password = password_hash($password, PASSWORD_BCRYPT);
            
            // Insert
            $stmt = $conn->prepare("INSERT INTO purchase_managers (name, email, password, phone, status) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param('sssss', $name, $email, $hashed_password, $phone, $status);
            
            if ($stmt->execute()) {
                $message = 'Purchase manager created successfully';
                $action = 'list';
            } else {
                if (strpos($conn->error, 'Duplicate entry') !== false) {
                    $error = 'Email already exists';
                } else {
                    $error = 'Error creating purchase manager: ' . $conn->error;
                }
            }
        }
    } elseif ($action === 'edit') {
        // Validate
        if (empty($name) || empty($email)) {
            $error = 'Name and email are required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email format';
        } elseif (empty($manager_id)) {
            $error = 'Invalid manager ID';
        } else {
            if (!empty($password)) {
                $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                $stmt = $conn->prepare("UPDATE purchase_managers SET name = ?, email = ?, password = ?, phone = ?, status = ? WHERE id = ?");
                $stmt->bind_param('sssssi', $name, $email, $hashed_password, $phone, $status, $manager_id);
            } else {
                $stmt = $conn->prepare("UPDATE purchase_managers SET name = ?, email = ?, phone = ?, status = ? WHERE id = ?");
                $stmt->bind_param('ssssi', $name, $email, $phone, $status, $manager_id);
            }
            
            if ($stmt->execute()) {
                $message = 'Purchase manager updated successfully';
                $action = 'list';
            } else {
                $error = 'Error updating purchase manager: ' . $conn->error;
            }
        }
    }
}

// Handle delete
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $stmt = $conn->prepare("DELETE FROM purchase_managers WHERE id = ?");
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        $message = 'Purchase manager deleted successfully';
    } else {
        $error = 'Error deleting purchase manager';
    }
    $action = 'list';
}

// Get all managers count for stats
$stats = ['total' => 0, 'active' => 0, 'inactive' => 0];
$result = $conn->query("SELECT status, COUNT(*) as count FROM purchase_managers GROUP BY status");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $stats['total'] += $row['count'];
        if ($row['status'] === 'active') {
            $stats['active'] = $row['count'];
        } else {
            $stats['inactive'] = $row['count'];
        }
    }
}
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="zytheme">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Purchase Managers - Admin">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">

    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Bootstrap CSS -->
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">

    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <title>Purchase Managers - Admin</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 0;
            z-index: 1000;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 30px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            text-align: center;
            border-bottom: 3px solid #d4a574;
        }

        .sidebar-logo {
            font-size: 40px;
            margin-bottom: 10px;
            display: block;
        }

        .sidebar-header h2 {
            font-size: 20px;
            margin: 10px 0 5px 0;
            font-weight: 700;
        }

        .sidebar-header p {
            font-size: 12px;
            opacity: 0.9;
            margin: 0;
        }

        .admin-name {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
        }

        .sidebar-menu li {
            margin: 0;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
            border-left: 3px solid transparent;
        }

        .sidebar-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-left-color: #d4a574;
            padding-left: 28px;
        }

        .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border-left-color: #d4a574;
        }

        .sidebar-menu i {
            width: 20px;
            text-align: center;
            font-size: 16px;
        }

        .sidebar-footer {
            position: absolute;
            width: 100%;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.1);
        }

        .logout-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
        }

        /* Top Header */
        .topbar {
            position: fixed;
            top: 0;
            left: 280px;
            right: 0;
            height: 70px;
            background: white;
            border-bottom: 1px solid #e8e8e8;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 999;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .topbar-title {
            font-size: 24px;
            font-weight: 700;
            color: #333;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .topbar-user {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 16px;
        }

        .btn-icon-small {
            width: 36px;
            height: 36px;
            border: none;
            border-radius: 6px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-icon-small:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .user-info p {
            margin: 0;
            font-size: 13px;
            color: #999;
        }

        .user-info strong {
            display: block;
            font-size: 14px;
            color: #333;
        }

        /* Main Content */
        .main-content {
            margin-left: 280px;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }

        .content-section {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
            display: flex;
            align-items: center;
            gap: 10px;
            color: #333;
        }

        .section-title i {
            color: #d4a574;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 12px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .btn-secondary {
            background: #f0f0f0;
            color: #333;
            border: 1px solid #e0e0e0;
        }

        .btn-secondary:hover {
            background: #e0e0e0;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .table-responsive {
            overflow-x: auto;
        }

        .admin-table {
            width: 100%;
            border-collapse: collapse;
        }

        .admin-table thead th {
            background: #f9f7f4;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #e8e8e8;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .admin-table tbody td {
            padding: 15px;
            border-bottom: 1px solid #e8e8e8;
            font-size: 14px;
        }

        .admin-table tbody tr:hover {
            background: #f9f9f9;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-badge.active {
            background: #d4edda;
            color: #155724;
        }

        .status-badge.inactive {
            background: #f8d7da;
            color: #721c24;
        }

        .action-btn {
            padding: 8px 16px;
            margin-right: 8px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn-edit {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
        }

        .btn-edit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .btn-delete {
            background: #c0392b;
            color: white;
        }

        .btn-delete:hover {
            background: #a93226;
            transform: translateY(-2px);
        }

        .form-group {
            margin-bottom: 20px;
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #333;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            padding: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .form-row .full-width {
            grid-column: 1 / -1;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            margin-top: 25px;
            padding-top: 25px;
            border-top: 1px solid #e0e0e0;
        }

        .form-actions button {
            flex: 1;
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .modal {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            overflow-y: auto;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: white;
            padding: 40px;
            border-radius: 10px;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
            margin: 20px;
        }

        .modal h2 {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 25px;
            color: #333;
        }

        .close-modal {
            position: absolute;
            right: 20px;
            top: 20px;
            font-size: 28px;
            cursor: pointer;
            color: #999;
            transition: color 0.3s ease;
            border: none;
            background: none;
            padding: 0;
        }

        .close-modal:hover {
            color: #333;
        }

        .menu-toggle {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            color: #333;
            cursor: pointer;
        }

        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 500;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .overlay.active {
            display: block;
            opacity: 1;
        }

        @media (max-width: 1200px) {
            .topbar-right {
                gap: 15px;
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 250px;
            }

            .topbar {
                left: 250px;
                padding: 0 20px;
            }

            .main-content {
                margin-left: 250px;
                padding: 20px;
            }

            .topbar-right {
                gap: 10px;
            }

            .user-info {
                display: none;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .admin-table thead th,
            .admin-table tbody td {
                padding: 10px;
                font-size: 12px;
            }

            .action-btn {
                padding: 6px 12px;
                font-size: 11px;
                margin-right: 4px;
            }
        }

        @media (max-width: 576px) {
            .sidebar {
                width: 250px;
                position: fixed;
                left: 0;
                top: 0;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                z-index: 1001;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .topbar {
                left: 0;
                padding: 0 15px;
                height: 60px;
            }

            .topbar-title {
                font-size: 18px;
            }

            .main-content {
                margin-left: 0;
                padding: 15px;
                margin-top: 60px;
            }

            .sidebar-header {
                padding: 20px 15px;
            }

            .sidebar-menu a {
                padding: 12px 15px;
            }

            .content-section {
                padding: 15px;
            }

            .menu-toggle {
                display: block;
            }

            .btn-group {
                flex-direction: column;
            }

            .btn-action {
                width: 100%;
                justify-content: center;
            }

            .btn-secondary {
                width: 100%;
                justify-content: center;
            }

            .modal-content {
                padding: 20px;
                width: 95%;
            }

            .form-actions {
                flex-direction: column;
            }

            .form-actions button {
                width: 100%;
            }
        }

        .swal2-container {
            z-index: 2000 !important;
        }

        .manager-count {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .count-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            border-left: 4px solid #d4a574;
        }

        .count-label {
            font-size: 12px;
            color: #888;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .count-value {
            font-size: 32px;
            font-weight: 700;
            color: #2c3e50;
        }
    </style>
</head>

<body>
    <!-- Overlay for mobile menu -->
    <div id="menuOverlay" class="overlay"></div>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-crown sidebar-logo"></i>
            <h2>Admin Portal</h2>
            <p>Granny Restaurant</p>
            <div class="admin-name" id="sidebarAdminName">Admin</div>
        </div>

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-th-large"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="blog.php"><i class="fas fa-blog"></i> <span>Blog</span></a></li>
            <li><a href="ingredients.php"><i class="fas fa-leaf"></i> <span>Ingredients</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span></a></li>
            <li><a href="orders.php"><i class="fas fa-file-invoice"></i> <span>Orders</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span></a></li>
            <li><a href="servers.php"><i class="fas fa-user-secret"></i> <span>Servers</span></a></li>
            <li><a href="purchase_managers.php" class="active"><i class="fas fa-handshake"></i> <span>Purchase Managers</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> <span>Settings</span></a></li>
        </ul>

        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </div>
    </div>

    <!-- Top Header -->
    <div class="topbar">
        <div style="display: flex; align-items: center; gap: 20px;">
            <button class="menu-toggle" id="menuToggle">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Purchase Managers</div>
        </div>

        <div class="topbar-right">
            <div class="topbar-user">
                <div class="user-avatar" id="userInitial">A</div>
                <div class="user-info">
                    <p>Welcome back</p>
                    <strong id="topbarUserName">Admin</strong>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?php echo $message; ?></span>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?php echo $error; ?></span>
            </div>
        <?php endif; ?>

        <?php if ($action === 'list'): ?>
            <!-- Manager Stats -->
            <div class="manager-count">
                <div class="count-card">
                    <div class="count-label">Total Managers</div>
                    <div class="count-value"><?php echo $stats['total']; ?></div>
                </div>
                <div class="count-card" style="border-left-color: #27ae60;">
                    <div class="count-label">Active</div>
                    <div class="count-value" style="color: #27ae60;"><?php echo $stats['active']; ?></div>
                </div>
                <div class="count-card" style="border-left-color: #c0392b;">
                    <div class="count-label">Inactive</div>
                    <div class="count-value" style="color: #c0392b;"><?php echo $stats['inactive']; ?></div>
                </div>
            </div>

            <!-- Managers List Section -->
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-list"></i>
                    All Purchase Managers
                </div>

                <div class="btn-group">
                    <button class="btn-action" onclick="openAddModal()">
                        <i class="fas fa-plus"></i> Add New Manager
                    </button>
                </div>

                <div class="table-responsive">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Last Login</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $result = $conn->query("SELECT id, name, email, phone, status, created_at, last_login FROM purchase_managers ORDER BY created_at DESC");
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $status_class = $row['status'] === 'active' ? 'active' : 'inactive';
                                    $status_text = ucfirst($row['status']);
                                    $last_login = $row['last_login'] ? date('M d, Y h:i A', strtotime($row['last_login'])) : 'Never';
                                    echo "
                                        <tr>
                                            <td><strong>{$row['name']}</strong></td>
                                            <td>{$row['email']}</td>
                                            <td>{$row['phone']}</td>
                                            <td><span class='status-badge $status_class'>$status_text</span></td>
                                            <td>" . date('M d, Y', strtotime($row['created_at'])) . "</td>
                                            <td>$last_login</td>
                                            <td>
                                                <button class='action-btn btn-edit' onclick=\"openEditModal({$row['id']}, '{$row['name']}', '{$row['email']}', '{$row['phone']}', '{$row['status']}')\"><i class='fas fa-edit'></i> Edit</button>
                                                <button class='action-btn btn-delete' onclick=\"if(confirm('Are you sure?')) location.href='?action=delete&id={$row['id']}'\"><i class='fas fa-trash'></i> Delete</button>
                                            </td>
                                        </tr>
                                    ";
                                }
                            } else {
                                echo "<tr><td colspan='7' style='text-align: center; color: #999; padding: 40px;'><i class='fas fa-inbox'></i> No purchase managers found</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Add/Edit Modal -->
    <div id="managerModal" class="modal">
        <div class="modal-content">
            <button class="close-modal" onclick="closeModal()">&times;</button>
            <h2 id="modalTitle">Add New Manager</h2>
            
            <form id="managerForm" method="POST">
                <input type="hidden" id="action" name="action" value="add">
                <input type="hidden" id="manager_id" name="manager_id" value="">

                <div class="form-row">
                    <div class="form-group">
                        <label for="name">Full Name *</label>
                        <input type="text" id="name" name="name" placeholder="Enter manager's name" required>
                    </div>
                    <div class="form-group">
                        <label for="email">Email Address *</label>
                        <input type="email" id="email" name="email" placeholder="Enter email address" required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="password">Password <span id="passwordRequired">*</span></label>
                        <input type="password" id="password" name="password" placeholder="Enter password (min 6 characters)" id="passwordInput">
                    </div>
                    <div class="form-group">
                        <label for="phone">Phone Number</label>
                        <input type="tel" id="phone" name="phone" placeholder="Enter phone number">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="status">Status</label>
                        <select id="status" name="status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-action" id="submitBtn">Create Manager</button>
                    <button type="button" class="btn-action btn-secondary" onclick="closeModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.js"></script>
    <script>
        // Mobile menu toggle
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const menuOverlay = document.getElementById('menuOverlay');

        if (menuToggle) {
            menuToggle.addEventListener('click', () => {
                sidebar.classList.toggle('active');
                menuOverlay.classList.toggle('active');
            });

            menuOverlay.addEventListener('click', () => {
                sidebar.classList.remove('active');
                menuOverlay.classList.remove('active');
            });
        }

        // Logout functionality
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', () => {
                Swal.fire({
                    title: 'Logout',
                    text: 'Are you sure you want to logout?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d4a574',
                    cancelButtonColor: '#999',
                    confirmButtonText: 'Logout'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = '../backend/admin_logout.php';
                    }
                });
            });
        }

        // Modal functions
        const modal = document.getElementById('managerModal');
        const managerForm = document.getElementById('managerForm');

        function openAddModal() {
            document.getElementById('action').value = 'add';
            document.getElementById('manager_id').value = '';
            document.getElementById('modalTitle').textContent = 'Add New Manager';
            document.getElementById('submitBtn').textContent = 'Create Manager';
            document.getElementById('passwordRequired').textContent = '*';
            document.getElementById('password').required = true;
            managerForm.reset();
            modal.classList.add('active');
        }

        function openEditModal(id, name, email, phone, status) {
            document.getElementById('action').value = 'edit';
            document.getElementById('manager_id').value = id;
            document.getElementById('modalTitle').textContent = 'Edit Manager';
            document.getElementById('submitBtn').textContent = 'Update Manager';
            document.getElementById('passwordRequired').textContent = '(Optional)';
            document.getElementById('password').required = false;
            document.getElementById('name').value = name;
            document.getElementById('email').value = email;
            document.getElementById('phone').value = phone;
            document.getElementById('status').value = status;
            document.getElementById('password').value = '';
            modal.classList.add('active');
        }

        function closeModal() {
            modal.classList.remove('active');
        }

        // Close modal on outside click
        window.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeModal();
            }
        });

        // Form submission
        managerForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const action = document.getElementById('action').value;
            const password = document.getElementById('password').value;

            if (action === 'add' && !password) {
                Swal.fire('Error', 'Password is required for new managers', 'error');
                return;
            }

            managerForm.submit();
        });

        // Admin name in sidebar
        document.getElementById('sidebarAdminName').textContent = 'Admin';
        document.getElementById('topbarUserName').textContent = 'Admin';
        document.getElementById('userInitial').textContent = 'A';
    </script>
</body>

</html>
