<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors on page
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_staff')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

// Handle create user
if (isset($_POST['create_user'])) {
    $username = db_prepare($con, $_POST['username']);
    $email = db_prepare($con, $_POST['email']);
    $password = md5($_POST['password']); // Hash password
    $role = db_prepare($con, $_POST['role']);
    $full_name = db_prepare($con, $_POST['full_name']);
    $phone = db_prepare($con, $_POST['phone']);

    // Check if email already exists
    $checkEmail = mysqli_query($con, "SELECT id FROM users WHERE email='$email'");

    if (mysqli_num_rows($checkEmail) > 0) {
        $_SESSION['error'] = "Email already exists!";
    } else {
        // Insert into users table
        $insertUser = mysqli_query($con, "INSERT INTO users (username, email, password, role) 
                                          VALUES ('$username', '$email', '$password', '$role')");

        if ($insertUser) {
            $userId = mysqli_insert_id($con);

            // Insert into user_details table
            mysqli_query($con, "INSERT INTO user_details (user_id, name, contactno) 
                               VALUES ('$userId', '$full_name', '$phone')");

            log_activity("Created Staff User", "Username: $username, Role: $role");
            $_SESSION['msg'] = "User account created successfully!";
        } else {
            $_SESSION['error'] = "Failed to create user: " . mysqli_error($con);
        }
    }
}

// Handle delete user
if (isset($_GET['del']) && isset($_GET['id'])) {
    $userId = intval($_GET['id']);

    // Check if trying to delete admin2 (system admin)
    $checkAdmin = mysqli_query($con, "SELECT username FROM users WHERE id='$userId'");
    $adminData = mysqli_fetch_assoc($checkAdmin);

    if ($adminData['username'] == 'admin2') {
        $_SESSION['error'] = "Cannot delete system administrator account (admin2)!";
    } else {
        $del_username = $adminData['username'];
        // Delete user and associated data
        mysqli_query($con, "DELETE FROM user_details WHERE user_id='$userId'");
        mysqli_query($con, "DELETE FROM users WHERE id='$userId'");
        log_activity("Deleted Staff account", "Username: $del_username, ID: $userId");
        $_SESSION['msg'] = "User deleted successfully!";
    }

    header('location: manage-staff.php');
    exit;
}

// Get all staff users (admin and staff roles)
$staffQuery = mysqli_query($con, "SELECT u.*, ud.name, ud.contactno 
                                  FROM users u 
                                  LEFT JOIN user_details ud ON u.id = ud.user_id 
                                  WHERE u.role IN ('admin', 'staff', 'sales')
                                  ORDER BY u.id ASC");
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Manage Staff - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-users-cog me-2"></i> Manage Staff</h1>
                            <p>Create and manage staff user accounts</p>
                        </div>
                        <div>
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
                                <i class="fas fa-user-plus me-2"></i>Create New User
                            </button>
                        </div>
                    </div>

                    <!-- Messages -->
                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <?php if (isset($_SESSION['error'])) { ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <!-- Staff Table -->
                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>Staff Members</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-hover" id="datatablesSimple">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th>Username</th>
                                        <th>Full Name</th>
                                        <th>Email</th>
                                        <th>Phone</th>
                                        <th>Role</th>
                                        <th>Created</th>
                                        <th width="10%">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $cnt = 1;
                                    while ($row = mysqli_fetch_array($staffQuery)) {
                                        $isSystemAdmin = ($row['username'] == 'admin2');
                                        $roleBadge = 'secondary';
                                        if ($row['role'] == 'admin')
                                            $roleBadge = 'danger';
                                        elseif ($row['role'] == 'sales')
                                            $roleBadge = 'info';
                                        elseif ($row['role'] == 'staff')
                                            $roleBadge = 'primary';
                                        ?>
                                        <tr>
                                            <td>
                                                <?php echo $cnt; ?>
                                            </td>
                                            <td>
                                                <strong>
                                                    <?php echo htmlentities($row['username']); ?>
                                                </strong>
                                                <?php if ($isSystemAdmin): ?>
                                                    <span class="badge bg-warning text-dark ms-2">
                                                        <i class="fas fa-shield-alt"></i> System Admin
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo htmlentities($row['name'] ?: 'N/A'); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlentities($row['email']); ?>
                                            </td>
                                            <td>
                                                <?php echo htmlentities($row['contactno'] ?: 'N/A'); ?>
                                            </td>
                                            <td><span class="badge bg-<?php echo $roleBadge; ?>">
                                                    <?php echo ucfirst($row['role']); ?>
                                                </span></td>
                                            <td>
                                                <?php echo date('M d, Y', strtotime($row['regDate'])); ?>
                                            </td>
                                            <td>
                                                <?php if ($isSystemAdmin): ?>
                                                    <button class="btn btn-sm btn-outline-secondary" disabled
                                                        title="Protected Account">
                                                        <i class="fas fa-lock"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <a href="edit-user.php?id=<?php echo $row['id']; ?>"
                                                        class="btn btn-sm btn-outline-primary me-2" title="Edit Staff"><i
                                                            class="fas fa-edit"></i></a>
                                                    <a href="manage-staff.php?del=1&id=<?php echo $row['id']; ?>"
                                                        class="btn btn-sm btn-outline-danger"
                                                        onclick="return confirm('Are you sure you want to delete this user?');"
                                                        title="Delete User">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php
                                        $cnt++;
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <!-- Create User Modal -->
    <div class="modal fade" id="createUserModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-plus me-2"></i>Create New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Username <span
                                        class="text-danger">*</span></label>
                                <input type="text" name="username" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Full Name <span
                                        class="text-danger">*</span></label>
                                <input type="text" name="full_name" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Email <span class="text-danger">*</span></label>
                                <input type="email" name="email" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Phone Number</label>
                                <input type="text" name="phone" class="form-control" placeholder="+233 123 456 789">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Password <span
                                        class="text-danger">*</span></label>
                                <input type="password" name="password" class="form-control" minlength="6" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Role <span class="text-danger">*</span></label>
                                <select name="role" class="form-select" required>
                                    <option value="">Select Role</option>
                                    <option value="admin">Admin (Full Access)</option>
                                    <option value="staff">Staff (Limited Access)</option>
                                    <option value="sales">Sales Person</option>
                                </select>
                            </div>
                        </div>

                        <div class="alert alert-info">
                            <strong><i class="fas fa-info-circle me-2"></i>Role Permissions:</strong>
                            <ul class="mb-0 mt-2">
                                <li><strong>Admin:</strong> Full access to all features</li>
                                <li><strong>Staff:</strong> Can manage products and orders</li>
                                <li><strong>Sales:</strong> Can view orders and customers</li>
                            </ul>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="create_user" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Create User
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>