<?php
/**
 * Staff Management Page (Admin Only)
 * Allows admins to create, edit, and manage staff members
 */

require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/helpers.php';

// Check if user is logged in and is admin
if (!isLoggedIn()) {
    header("Location: admin-login.php");
    exit();
}

$currentUser = getCurrentUser();
if (!isset($currentUser['user_type']) || $currentUser['user_type'] !== 'admin') {
    header("Location: admin-login.php");
    exit();
}

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? trim($_POST['action']) : '';

    if ($action === 'add_staff') {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if (empty($firstName) || empty($lastName) || empty($email) || empty($password)) {
            $message = 'All fields are required';
            $messageType = 'danger';
        } elseif ($password !== $confirmPassword) {
            $message = 'Passwords do not match';
            $messageType = 'danger';
        } elseif (strlen($password) < 6) {
            $message = 'Password must be at least 6 characters';
            $messageType = 'danger';
        } else {
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO users (first_name, last_name, email, phone, password, user_type, is_active) VALUES (?, ?, ?, ?, ?, 'staff', 1)");

            if ($stmt) {
                $stmt->bind_param('sssss', $firstName, $lastName, $email, $phone, $hashedPassword);
                if ($stmt->execute()) {
                    $message = "Staff member '$firstName $lastName' created successfully";
                    $messageType = 'success';
                } else {
                    if (strpos($stmt->error, 'Duplicate entry') !== false) {
                        $message = 'Email already exists';
                    } else {
                        $message = 'Error creating staff member: ' . $stmt->error;
                    }
                    $messageType = 'danger';
                }
                $stmt->close();
            }
        }
    } elseif ($action === 'toggle_status') {
        $staffId = (int)($_POST['staff_id'] ?? 0);
        if ($staffId > 0) {
            $stmt = $conn->prepare("UPDATE users SET is_active = NOT is_active WHERE id = ? AND user_type = 'staff'");
            if ($stmt) {
                $stmt->bind_param('i', $staffId);
                if ($stmt->execute()) {
                    $message = 'Staff status updated successfully';
                    $messageType = 'success';
                } else {
                    $message = 'Error updating staff status';
                    $messageType = 'danger';
                }
                $stmt->close();
            }
        }
    }
}

// Get all staff members
$staffMembers = [];
try {
    $result = $conn->query("SELECT id, first_name, last_name, email, phone, is_active, created_at FROM users WHERE user_type = 'staff' ORDER BY created_at DESC");
    if ($result) {
        $staffMembers = $result->fetch_all(MYSQLI_ASSOC) ?? [];
    }
} catch (Exception $e) {
    error_log("Error fetching staff members: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Manage Staff | Almaris Hotel Management</title>
    <link rel="icon" href="images/icon.webp" type="image/gif" sizes="16x16">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Manage staff members in Almaris hotel management system.">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="css/plugins.css" rel="stylesheet" type="text/css">
    <link href="css/style.css" rel="stylesheet" type="text/css">
    <link href="css/coloring.css" rel="stylesheet" type="text/css">
    <link href="css/admin.css" rel="stylesheet" type="text/css">
    <link id="colors" href="css/colors/scheme-01.css" rel="stylesheet" type="text/css">
</head>

<body class="light">
    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
        <div class="container-fluid px-3 px-md-4">
            <a class="navbar-brand d-flex align-items-center" href="admin-dashboard.php">
                <img src="images/icon.webp" alt="Almaris" style="max-height: 40px; margin-right: 10px;">
                <span>Almaris Admin</span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#adminNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="adminNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="admin-dashboard.php">Dashboard</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="manage-staff.php">Manage Staff</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="logout.php">Logout</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div style="min-height: calc(100vh - 80px); background: #f5f5f5; padding: 30px 0;">
        <div class="container-fluid px-3 px-md-4">
            <!-- Header -->
            <div class="row mb-4">
                <div class="col-12">
                    <div style="background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);">
                        <h1 style="margin: 0; color: #333;">
                            <i class="icofont-users-alt-5"></i> Manage Staff Members
                        </h1>
                        <p style="margin-top: 8px; color: #666;">Add, edit, and manage your staff team</p>
                    </div>
                </div>
            </div>

            <!-- Message Display -->
            <?php if ($message): ?>
            <div class="row mb-4">
                <div class="col-12">
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                        <i class="icofont-<?php echo $messageType === 'success' ? 'check-circled' : 'close-circled'; ?>"></i>
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Add Staff Form -->
            <div class="row mb-4">
                <div class="col-12 col-lg-5">
                    <div style="background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);">
                        <h4 style="margin-bottom: 20px; color: #333;">
                            <i class="icofont-plus-circle" style="color: #667eea;"></i> Add New Staff Member
                        </h4>

                        <form method="POST" action="">
                            <input type="hidden" name="action" value="add_staff">

                            <div class="mb-3">
                                <label for="first_name" class="form-label">First Name *</label>
                                <input type="text" id="first_name" name="first_name" class="form-control" required>
                            </div>

                            <div class="mb-3">
                                <label for="last_name" class="form-label">Last Name *</label>
                                <input type="text" id="last_name" name="last_name" class="form-control" required>
                            </div>

                            <div class="mb-3">
                                <label for="email" class="form-label">Email Address *</label>
                                <input type="email" id="email" name="email" class="form-control" required>
                            </div>

                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone Number</label>
                                <input type="tel" id="phone" name="phone" class="form-control">
                            </div>

                            <div class="mb-3">
                                <label for="password" class="form-label">Password *</label>
                                <input type="password" id="password" name="password" class="form-control" required>
                                <small class="text-muted">Minimum 6 characters</small>
                            </div>

                            <div class="mb-3">
                                <label for="confirm_password" class="form-label">Confirm Password *</label>
                                <input type="password" id="confirm_password" name="confirm_password" class="form-control" required>
                            </div>

                            <button type="submit" class="btn btn-primary w-100">
                                <i class="icofont-plus"></i> Create Staff Member
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Staff List -->
                <div class="col-12 col-lg-7">
                    <div style="background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.1);">
                        <h4 style="margin-bottom: 20px; color: #333;">
                            <i class="icofont-list" style="color: #667eea;"></i> Current Staff Members
                        </h4>

                        <?php if (count($staffMembers) > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead style="background: #f8f9fa;">
                                        <tr>
                                            <th>Name</th>
                                            <th class="d-none d-md-table-cell">Email</th>
                                            <th class="d-none d-md-table-cell">Status</th>
                                            <th class="text-end">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($staffMembers as $staff): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($staff['first_name'] . ' ' . $staff['last_name']); ?></strong>
                                                <br>
                                                <small class="text-muted d-md-none"><?php echo htmlspecialchars($staff['email']); ?></small>
                                            </td>
                                            <td class="d-none d-md-table-cell">
                                                <small><?php echo htmlspecialchars($staff['email']); ?></small>
                                            </td>
                                            <td class="d-none d-md-table-cell">
                                                <span class="badge <?php echo $staff['is_active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                    <?php echo $staff['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                            <td class="text-end">
                                                <form method="POST" action="" style="display: inline;">
                                                    <input type="hidden" name="action" value="toggle_status">
                                                    <input type="hidden" name="staff_id" value="<?php echo $staff['id']; ?>">
                                                    <button type="submit" class="btn btn-sm <?php echo $staff['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                                        <i class="icofont-<?php echo $staff['is_active'] ? 'close-circled' : 'check-circled'; ?>"></i>
                                                        <?php echo $staff['is_active'] ? 'Deactivate' : 'Activate'; ?>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div style="text-align: center; padding: 40px 20px; color: #999;">
                                <i class="icofont-users-alt-5" style="font-size: 48px; display: block; margin-bottom: 15px;"></i>
                                <p>No staff members yet. Create one using the form on the left.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Info Box -->
            <div class="row">
                <div class="col-12">
                    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px;">
                        <h5 style="margin-bottom: 10px;">
                            <i class="icofont-info-circle"></i> Staff Login Access
                        </h5>
                        <p style="margin: 0;">
                            Staff members can log in at: <strong>staff-login.php</strong><br>
                            Dashboard URL: <strong>staff-dashboard.php</strong>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>

</html>
