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

include 'db_connect.php';

if (empty($_GET['id'])) {
    die("No user selected.");
}
$user_id = (int)$_GET['id'];

$page_title = "Edit User";
$message    = "";

/* Fetch existing user */
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$userResult = $stmt->get_result();
$user       = $userResult->fetch_assoc();
$stmt->close();

if (!$user) {
    die("User not found.");
}

/* Handle POST update */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_user'])) {
    $username      = trim($_POST['username'] ?? '');
    $role          = trim($_POST['role'] ?? '');
    $new_password  = trim($_POST['password'] ?? '');

    $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          = trim($_POST['phone'] ?? '');

    // IMPORTANT: use a variable for date_of_birth when binding (not an inline expression)
    $date_of_birth_param = $date_of_birth !== '' ? $date_of_birth : null;

    if ($username === '' || $role === '') {
        $message = "<div class='alert alert-error'>Username and role are required.</div>";
    } else {
        $hasError = false;

        // 1) Check duplicate username (excluding this user)
        if (!$hasError) {
            $checkUsername = $conn->prepare("SELECT id FROM users WHERE username = ? AND id <> ?");
            if ($checkUsername) {
                $checkUsername->bind_param("si", $username, $user_id);
                $checkUsername->execute();
                $resUser = $checkUsername->get_result();
                if ($resUser && $resUser->num_rows > 0) {
                    $message = "<div class='alert alert-error'>Username already exists. Choose another one.</div>";
                    $hasError = true;
                }
                $checkUsername->close();
            } else {
                $message = "<div class='alert alert-error'>Error checking username: " .
                           htmlspecialchars($conn->error) . "</div>";
                $hasError = true;
            }
        }

        // 2) Check duplicate ID number (if provided, excluding this user)
        if (!$hasError && $id_number !== '') {
            $checkId = $conn->prepare("SELECT id FROM users WHERE id_number = ? AND id <> ?");
            if ($checkId) {
                $checkId->bind_param("si", $id_number, $user_id);
                $resId = $checkId->execute() ? $checkId->get_result() : false;
                if ($resId && $resId->num_rows > 0) {
                    $message = "<div class='alert alert-error'>ID number already exists for another user.</div>";
                    $hasError = true;
                }
                $checkId->close();
            } else {
                $message = "<div class='alert alert-error'>Error checking ID number: " .
                           htmlspecialchars($conn->error) . "</div>";
                $hasError = true;
            }
        }

        // 3) Check duplicate phone number (if provided, excluding this user)
        if (!$hasError && $phone !== '') {
            $checkPhone = $conn->prepare("SELECT id FROM users WHERE phone_number = ? AND id <> ?");
            if ($checkPhone) {
                $checkPhone->bind_param("si", $phone, $user_id);
                $resPhone = $checkPhone->execute() ? $checkPhone->get_result() : false;
                if ($resPhone && $resPhone->num_rows > 0) {
                    $message = "<div class='alert alert-error'>Phone number already exists for another user.</div>";
                    $hasError = true;
                }
                $checkPhone->close();
            } else {
                $message = "<div class='alert alert-error'>Error checking phone number: " .
                           htmlspecialchars($conn->error) . "</div>";
                $hasError = true;
            }
        }

        // Only proceed with UPDATE if no duplicate errors
        if (!$hasError) {
            if ($new_password !== '') {
                // update password as well
                $hashed = password_hash($new_password, PASSWORD_DEFAULT);
                $update = $conn->prepare("
                    UPDATE users
                    SET username = ?, role = ?, password = ?, 
                        first_name = ?, last_name = ?, date_of_birth = ?, 
                        id_number = ?, place_of_birth = ?, gender = ?, phone_number = ?
                    WHERE id = ?
                ");

                if (!$update) {
                    $message = "<div class='alert alert-error'>Prepare failed: " . htmlspecialchars($conn->error) . "</div>";
                } else {
                    $update->bind_param(
                        "ssssssssssi",
                        $username,
                        $role,
                        $hashed,
                        $first_name,
                        $last_name,
                        $date_of_birth_param,
                        $id_number,
                        $place_of_birth,
                        $gender,
                        $phone,
                        $user_id
                    );
                }
            } else {
                // keep existing password
                $update = $conn->prepare("
                    UPDATE users
                    SET username = ?, role = ?, 
                        first_name = ?, last_name = ?, date_of_birth = ?, 
                        id_number = ?, place_of_birth = ?, gender = ?, phone_number = ?
                    WHERE id = ?
                ");

                if (!$update) {
                    $message = "<div class='alert alert-error'>Prepare failed: " . htmlspecialchars($conn->error) . "</div>";
                } else {
                    $update->bind_param(
                        "sssssssssi",
                        $username,
                        $role,
                        $first_name,
                        $last_name,
                        $date_of_birth_param,
                        $id_number,
                        $place_of_birth,
                        $gender,
                        $phone,
                        $user_id
                    );
                }
            }

            if (isset($update) && $update) {
                if ($update->execute()) {
                    $message = "<div class='alert alert-success'>User updated successfully.</div>";

                    // refresh $user data
                    $update->close();
                    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                    $stmt->bind_param("i", $user_id);
                    $stmt->execute();
                    $user = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                } else {
                    $message = "<div class='alert alert-error'>Error updating user: " .
                               htmlspecialchars($update->error) . "</div>";
                    $update->close();
                }
            }
        }
    }
}
?>
<!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);
        }

        /* Layout next to sidebar */
        .content-area {
            margin-left: 260px;
            padding: 28px 32px 32px;
            min-height: 100vh;
            box-sizing: border-box;
        }

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

        .page-header {
            max-width: 1100px;
            margin: 0 auto 18px;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 8px;
        }

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

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

        .page-header-right a.back-link-top {
            font-size: 13px;
            text-decoration: none;
            color: var(--accent-gold);
        }

        .page-header-right a.back-link-top:hover {
            text-decoration: underline;
        }

        /* Main card */
        .page-layout {
            max-width: 1100px;
            margin: 0 auto;
        }

        .page-card {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 22px 26px 26px;
            box-shadow: 0 10px 28px 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 14px 34px rgba(15,23,42,0.10);
        }

        .section-title {
            font-size: 15px;
            font-weight: 600;
            color: var(--text-heading);
            margin-bottom: 12px;
        }

        /* Alerts */
        .alert {
            margin-bottom: 12px;
            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;
        }

        /* Form grid */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px 18px;
        }

        @media (max-width: 800px) {
            .form-grid {
                grid-template-columns: minmax(0, 1fr);
            }
        }

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

        .field-group label {
            font-size: 13px;
            font-weight: 500;
            color: var(--text-heading);
        }

        .field-group small {
            font-size: 11px;
            color: #9ca3af;
        }

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

        .field-group input:focus,
        .field-group 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"] .field-group input,
        body[data-theme="light"] .field-group select {
            background: #ffffff;
            color: #111827;
            border-color: #cbd5f5;
        }

        .save-row {
            margin-top: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .save-btn {
            padding: 9px 18px;
            background-color: var(--accent-gold);
            color: var(--bg-main);
            border-radius: 999px;
            border: none;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            min-width: 150px;
            text-align: center;
        }

        .save-btn:hover {
            background-color: var(--accent-gold-soft);
        }

        .back-link-bottom {
            font-size: 13px;
            color: var(--accent-gold);
            text-decoration: none;
        }
        .back-link-bottom:hover {
            text-decoration: underline;
        }

        footer {
            background: transparent;
        }
    </style>
</head>
<body>
<?php include 'sidebar.php'; ?>

<div class="content-area">

    <div class="page-header">
        <div>
            <div class="page-title">Edit User #<?= (int)$user['id']; ?></div>
            <div class="page-subtitle">Update personal and account details for this user.</div>
        </div>
        <div class="page-header-right">
            <a href="manage_users.php" class="back-link-top">← Back to users</a>
        </div>
    </div>

    <div class="page-layout">
        <div class="page-card">
            <?php if (!empty($message)) echo $message; ?>

            <div class="section-title">User Details</div>

            <form method="post">
                <div class="form-grid">
                    <!-- Account info -->
                    <div class="field-group">
                        <label for="username">Username *</label>
                        <input type="text" id="username" name="username"
                               value="<?= htmlspecialchars($user['username']); ?>" required>
                    </div>

                    <div class="field-group">
                        <label for="role">Role *</label>
                        <select id="role" name="role" required>
                            <option value="admin"   <?= $user['role'] === 'admin'   ? 'selected' : '' ?>>Admin</option>
                            <option value="cashier" <?= $user['role'] === 'cashier' ? 'selected' : '' ?>>Cashier</option>
                        </select>
                    </div>

                    <div class="field-group">
                        <label for="password">New password</label>
                        <input type="password" id="password" name="password">
                        <small>Leave blank to keep the current password.</small>
                    </div>

                    <!-- Personal info -->
                    <div class="field-group">
                        <label for="first_name">First name</label>
                        <input type="text" id="first_name" name="first_name"
                               value="<?= htmlspecialchars($user['first_name'] ?? ''); ?>">
                    </div>

                    <div class="field-group">
                        <label for="last_name">Last name</label>
                        <input type="text" id="last_name" name="last_name"
                               value="<?= htmlspecialchars($user['last_name'] ?? ''); ?>">
                    </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"
                               value="<?= htmlspecialchars($user['date_of_birth'] ?? ''); ?>">
                    </div>

                    <div class="field-group">
                        <label for="id_number">ID number</label>
                        <input type="text" id="id_number" name="id_number"
                               value="<?= htmlspecialchars($user['id_number'] ?? ''); ?>">
                    </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"
                               value="<?= htmlspecialchars($user['place_of_birth'] ?? ''); ?>">
                    </div>

                    <div class="field-group">
                        <label for="gender">Gender</label>
                        <select id="gender" name="gender">
                            <option value="" <?= empty($user['gender']) ? 'selected' : '' ?>>-- select gender --</option>
                            <option value="male"   <?= ($user['gender'] ?? '') === 'male'   ? 'selected' : '' ?>>Male</option>
                            <option value="female" <?= ($user['gender'] ?? '') === 'female' ? 'selected' : '' ?>>Female</option>
                            <option value="other"  <?= ($user['gender'] ?? '') === 'other'  ? 'selected' : '' ?>>Other</option>
                        </select>
                    </div>

                    <div class="field-group">
                        <label for="phone">Phone number</label>
                        <input type="text" id="phone" name="phone"
                               value="<?= htmlspecialchars($user['phone_number'] ?? ''); ?>">
                    </div>
                </div>

                <div class="save-row">
                    <button type="submit" name="save_user" class="save-btn">Save changes</button>
                    <a href="manage_users.php" class="back-link-bottom">← Back to users</a>
                </div>
            </form>
        </div>
    </div>
</div>

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