<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.html?error=unauthorized");
    exit();
}

include 'db_connect.php';

$page_title = "Manage Users";

$message = "";

/* -----------------------------
   HANDLE ADD NEW USER
------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_user'])) {
    $new_username    = trim($_POST['username']        ?? '');
    $new_password    = trim($_POST['password']        ?? '');
    $new_role        = trim($_POST['role']            ?? '');
    $first_name      = trim($_POST['first_name']      ?? '');
    $last_name       = trim($_POST['last_name']       ?? '');
    $date_of_birth   = trim($_POST['date_of_birth']   ?? '');
    $id_number       = trim($_POST['id_number']       ?? '');
    $place_of_birth  = trim($_POST['place_of_birth']  ?? '');
    $gender          = trim($_POST['gender']          ?? '');
    $phone_number    = trim($_POST['phone_number']    ?? '');

    // Basic validation – required fields
    if (
        $new_username  === '' ||
        $new_password  === '' ||
        $new_role      === '' ||
        $first_name    === '' ||
        $last_name     === '' ||
        $date_of_birth === '' ||
        $id_number     === '' ||
        $gender        === '' ||
        $phone_number  === ''
    ) {
        $message = "<div class='alert alert-error'>Please fill in all required fields.</div>";
    } else {

        /* -----------------------------
           CHECK UNIQUE CONSTRAINTS
           - username
           - id_number
           - phone_number
        ------------------------------ */
        $hasError  = false;
        $errorText = [];

        // 1) Username
        $checkUsername = $conn->prepare("SELECT id FROM users WHERE username = ?");
        if (!$checkUsername) {
            $message = "<div class='alert alert-error'>Error preparing username check: " .
                       htmlspecialchars($conn->error) . "</div>";
            $hasError = true;
        } else {
            $checkUsername->bind_param("s", $new_username);
            $checkUsername->execute();
            $resUser = $checkUsername->get_result();
            if ($resUser && $resUser->num_rows > 0) {
                $errorText[] = "Username already exists. Choose another one.";
                $hasError = true;
            }
            $checkUsername->close();
        }

        // 2) ID Number (only if no previous fatal error)
        if (!$hasError && $id_number !== '') {
            $checkID = $conn->prepare("SELECT id FROM users WHERE id_number = ?");
            if (!$checkID) {
                $message = "<div class='alert alert-error'>Error preparing ID number check: " .
                           htmlspecialchars($conn->error) . "</div>";
                $hasError = true;
            } else {
                $checkID->bind_param("s", $id_number);
                $checkID->execute();
                $resID = $checkID->get_result();
                if ($resID && $resID->num_rows > 0) {
                    $errorText[] = "ID Number already exists. Please verify it.";
                    $hasError = true;
                }
                $checkID->close();
            }
        }

        // 3) Phone number (only if no previous fatal error)
        if (!$hasError && $phone_number !== '') {
            $checkPhone = $conn->prepare("SELECT id FROM users WHERE phone_number = ?");
            if (!$checkPhone) {
                $message = "<div class='alert alert-error'>Error preparing phone number check: " .
                           htmlspecialchars($conn->error) . "</div>";
                $hasError = true;
            } else {
                $checkPhone->bind_param("s", $phone_number);
                $checkPhone->execute();
                $resPhone = $checkPhone->get_result();
                if ($resPhone && $resPhone->num_rows > 0) {
                    $errorText[] = "Phone number already exists. Please use a different one.";
                    $hasError = true;
                }
                $checkPhone->close();
            }
        }

        // If any uniqueness issue, show combined message and stop
        if ($hasError && !empty($errorText)) {
            $message = "<div class='alert alert-error'>" . implode("<br>", $errorText) . "</div>";
        }

        // If no errors at all, proceed to insert
        if (!$hasError) {
            // Hash password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

            $insertStmt = $conn->prepare("
                INSERT INTO users (
                    username,
                    password,
                    role,
                    first_name,
                    last_name,
                    date_of_birth,
                    id_number,
                    place_of_birth,
                    gender,
                    phone_number
                ) VALUES (?,?,?,?,?,?,?,?,?,?)
            ");

            if (!$insertStmt) {
                $message = "<div class='alert alert-error'>Error preparing insert: " .
                           htmlspecialchars($conn->error) . "</div>";
            } else {
                $insertStmt->bind_param(
                    "ssssssssss",
                    $new_username,
                    $hashed_password,
                    $new_role,
                    $first_name,
                    $last_name,
                    $date_of_birth,
                    $id_number,
                    $place_of_birth,
                    $gender,
                    $phone_number
                );

                if ($insertStmt->execute()) {
                    $message = "<div class='alert alert-success'>User <strong>" .
                               htmlspecialchars($new_username) .
                               "</strong> added successfully.</div>";
                } else {
                    $message = "<div class='alert alert-error'>Error adding user: " .
                               htmlspecialchars($insertStmt->error) . "</div>";
                }
                $insertStmt->close();
            }
        }
    }
}

/* -----------------------------
   FETCH ALL USERS
------------------------------ */
$sql    = "SELECT * FROM users ORDER BY id DESC";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include('head.php'); ?>

    <style>
        body {
            font-family: 'Poppins', Arial, sans-serif;
            background: var(--bg-main);
            margin: 0;
            color: var(--text-main);
        }

        /* Content to the right of sidebar */
        .content-area {
            margin-left: 260px;
            padding: 25px 30px;
        }

        @media(max-width: 768px) {
            .content-area {
                margin-left: 80px;
                padding: 20px;
            }
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 18px;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-heading);
        }

        .page-subtitle {
            font-size: 13px;
            color: var(--accent-gold);
            margin-top: 4px;
        }

        /* Card around table + form */
        .page-card {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 18px 22px 22px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.35);
            border: 1px solid #0a4a85;
            color: var(--text-main);
        }

        body[data-theme="light"] .page-card {
            border-color: rgba(148,163,184,0.55);
            box-shadow: 0 12px 28px rgba(15,23,42,0.10);
        }

        .page-card-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 10px;
            color: var(--text-heading);
        }

        /* Alerts */
        .alert {
            margin-bottom: 10px;
            padding: 8px 10px;
            border-radius: 10px;
            font-size: 13px;
            border-left-width: 4px;
            border-left-style: solid;
        }
        .alert-success {
            background: rgba(34,197,94,0.12);
            border-left-color: rgba(34,197,94,0.9);
            color: #bbf7d0;
        }
        .alert-error {
            background: rgba(239,68,68,0.14);
            border-left-color: rgba(248,113,113,0.95);
            color: #fecaca;
        }
        body[data-theme="light"] .alert-success {
            background: #dcfce7;
            border-left-color: #16a34a;
            color: #166534;
        }
        body[data-theme="light"] .alert-error {
            background: #fee2e2;
            border-left-color: #ef4444;
            color: #b91c1c;
        }

        /* Add user form */
        .add-user-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 10px 14px;
            margin-bottom: 14px;
            align-items: flex-end;
        }

        .add-user-form .field-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .add-user-form label {
            font-size: 13px;
            font-weight: 500;
            color: var(--text-heading);
        }

        .add-user-form input,
        .add-user-form select {
            padding: 8px 10px;
            border-radius: 8px;
            border: 1px solid #0a4a85;
            background: #011b3d;
            color: #e5e7eb;
            font-size: 13px;
        }

        .add-user-form input:focus,
        .add-user-form select:focus {
            outline: none;
            border-color: var(--accent-gold);
            box-shadow: 0 0 0 1px rgba(250,204,21,0.3);
        }

        body[data-theme="light"] .add-user-form input,
        body[data-theme="light"] .add-user-form select {
            background: #ffffff;
            color: #111827;
            border-color: #cbd5f5;
        }

        .add-button-submit {
            padding: 9px 16px;
            background-color: var(--accent-gold);
            color: var(--bg-main);
            border-radius: 8px;
            border: none;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            transition: 0.2s;
            width: 100%;
        }

        .add-button-submit:hover {
            background-color: var(--accent-gold-soft);
        }

        /* Table */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 6px;
        }

        table {
            width: 100%;
            min-width: 850px;
            margin: 0 auto;
            border-collapse: collapse;
            background: var(--bg-card);
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 6px 15px rgba(0,0,0,0.3);
            color: var(--text-main);
        }

        thead tr {
            background: var(--bg-table-head);
        }

        th,
        td {
            padding: 10px 12px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.15);
            font-size: 13px;
            white-space: nowrap;
        }

        th {
            color: #ffffff;
            font-weight: 600;
        }

        tbody tr {
            background: var(--bg-table-row);
        }

        tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        tbody tr:hover {
            background: var(--bg-table-hover);
            color: #ffffff;
        }

        /* Light theme tweaks for table */
        body[data-theme="light"] th,
        body[data-theme="light"] td {
            border-color: rgba(148,163,184,0.4);
        }

        body[data-theme="light"] th {
            color: #111827;
        }

        body[data-theme="light"] tbody tr {
            background: var(--bg-table-row);
        }

        body[data-theme="light"] tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        body[data-theme="light"] tbody tr:hover {
            background: var(--bg-table-hover);
            color: #111827;
        }

        /* Actions */
        .actions a {
            padding: 6px 10px;
            margin: 0 3px;
            border-radius: 5px;
            text-decoration: none;
            color: #ffffff;
            font-weight: 500;
            font-size: 12px;
            display: inline-block;
        }

        .view {
            background: #16a34a;
        }
        .view:hover {
            background: #15803d;
        }

        .edit {
            background: #3498db;
        }
        .edit:hover {
            background: #2980b9;
        }

        .delete {
            background: #e74c3c;
        }
        .delete:hover {
            background: #c0392b;
        }

        @media(max-width: 768px) {
            th,
            td {
                font-size: 12px;
            }

            .add-button-submit {
                width: 100%;
            }
        }

        footer {
            background: transparent;
        }
    </style>
</head>

<body>

<?php include('sidebar.php'); ?>

<div class="content-area">

    <div class="page-header">
        <div>
            <div class="page-title">Manage Users</div>
            <div class="page-subtitle">Add, view and update system user accounts</div>
        </div>
    </div>

    <div class="page-card">
        <div class="page-card-title">Add New User</div>

        <?php if (!empty($message)): ?>
            <?= $message ?>
        <?php endif; ?>

        <!-- INLINE ADD USER FORM -->
        <form method="post" class="add-user-form">
            <div class="field-group">
                <label for="username">Username *</label>
                <input type="text" id="username" name="username" required>
            </div>

            <div class="field-group">
                <label for="password">Password *</label>
                <input type="password" id="password" name="password" required>
            </div>

            <div class="field-group">
                <label for="role">Role *</label>
                <select id="role" name="role" required>
                    <option value="">-- select role --</option>
                    <option value="admin">Admin</option>
                    <option value="cashier">Cashier</option>
                </select>
            </div>

            <div class="field-group">
                <label for="first_name">First Name *</label>
                <input type="text" id="first_name" name="first_name" required>
            </div>

            <div class="field-group">
                <label for="last_name">Last Name *</label>
                <input type="text" id="last_name" name="last_name" required>
            </div>

            <div class="field-group">
                <label for="date_of_birth">Date of Birth *</label>
                <input type="date" id="date_of_birth" name="date_of_birth" required>
            </div>

            <div class="field-group">
                <label for="id_number">ID Number *</label>
                <input type="text" id="id_number" name="id_number" required>
            </div>

            <div class="field-group">
                <label for="place_of_birth">Place of Birth</label>
                <input type="text" id="place_of_birth" name="place_of_birth">
            </div>

            <div class="field-group">
                <label for="gender">Gender *</label>
                <select id="gender" name="gender" required>
                    <option value="">-- select gender --</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                    <option value="Other">Other</option>
                </select>
            </div>

            <div class="field-group">
                <label for="phone_number">Phone Number *</label>
                <input type="text" id="phone_number" name="phone_number" required>
            </div>

            <div class="field-group">
                <button type="submit" name="add_user" class="add-button-submit">
                    + Add User
                </button>
            </div>
        </form>

        <hr style="border-color: rgba(148,163,184,0.3); margin: 12px 0 16px;">

        <div class="page-card-title">User List</div>

        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Full Name</th>
                        <th>Role</th>
                        <th>Phone</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= (int)$row['id']; ?></td>
                            <td><?= htmlspecialchars($row['username']); ?></td>
                            <td>
                                <?= htmlspecialchars(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''))); ?>
                            </td>
                            <td><?= ucfirst(htmlspecialchars($row['role'])); ?></td>
                            <td><?= htmlspecialchars($row['phone_number'] ?? ''); ?></td>
                            <td class="actions">
                                <a class="view" href="view_user.php?id=<?= (int)$row['id']; ?>">View</a>
                                <a class="edit" href="edit_user.php?id=<?= (int)$row['id']; ?>">Edit</a>
                                <a class="delete" href="delete_user.php?id=<?= (int)$row['id']; ?>"
                                   onclick="return confirm('Delete this user?');">
                                   Delete
                                </a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="6">No users found.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<?php include 'footer.php'; ?>
</body>
</html>
