<?php
require_once 'includes/auth_check.php';
$page = 'profile'; // A unique page name
require_once '../config/database.php';
require_once '../includes/functions.php';

$database = new Database();
$db = $database->getConnection();
$admin_id = $_SESSION['admin_id'];

// --- Handle Form Submissions (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Check
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error_message'] = "Invalid security token. Please try again.";
    } else {
        // Check which form was submitted
        if (isset($_POST['action']) && $_POST['action'] === 'update_profile') {
            // --- Update Profile Logic ---
            $first_name = trim($_POST['first_name']);
            $last_name = trim($_POST['last_name']);
            $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);

            if (empty($first_name) || empty($last_name) || empty($email)) {
                $_SESSION['error_message'] = "Please fill in all profile fields.";
            } else {
                try {
                    $stmt = $db->prepare("UPDATE admin_users SET first_name = ?, last_name = ?, email = ? WHERE id = ?");
                    $stmt->execute([$first_name, $last_name, $email, $admin_id]);
                    $_SESSION['success_message'] = "Your profile has been updated successfully.";
                    // Update session name for immediate reflection
                    $_SESSION['admin_name'] = $first_name;
                } catch (PDOException $e) {
                    $_SESSION['error_message'] = "A database error occurred while updating your profile.";
                    error_log("Admin Profile Update Error: " . $e->getMessage());
                }
            }
        } elseif (isset($_POST['action']) && $_POST['action'] === 'change_password') {
            // --- Change Password Logic ---
            $current_password = $_POST['current_password'];
            $new_password = $_POST['new_password'];
            $confirm_password = $_POST['confirm_password'];

            if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
                $_SESSION['error_message'] = "Please fill in all password fields.";
            } elseif ($new_password !== $confirm_password) {
                $_SESSION['error_message'] = "New password and confirmation do not match.";
            } elseif (strlen($new_password) < 8) {
                $_SESSION['error_message'] = "New password must be at least 8 characters long.";
            } else {
                // Fetch current password from DB to verify
                $stmt = $db->prepare("SELECT password FROM admin_users WHERE id = ?");
                $stmt->execute([$admin_id]);
                $admin = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($admin && password_verify($current_password, $admin['password'])) {
                    // Current password is correct, proceed to update
                    $hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $update_stmt = $db->prepare("UPDATE admin_users SET password = ? WHERE id = ?");
                    $update_stmt->execute([$hashed_new_password, $admin_id]);
                    $_SESSION['success_message'] = "Your password has been changed successfully.";
                } else {
                    $_SESSION['error_message'] = "The current password you entered is incorrect.";
                }
            }
        }
    }
    // Redirect to the same page to show messages and prevent form resubmission
    header("Location: profile.php");
    exit;
}

// --- Fetch Admin Data for Form (GET Request) ---
$stmt = $db->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->execute([$admin_id]);
$admin_user = $stmt->fetch(PDO::FETCH_ASSOC);

// Generate a CSRF token for the forms
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

include 'includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Admin Profile</h1>

    <!-- Display Success/Error Messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="card shadow mb-4">
        <div class="card-body">
            <!-- Tab Navigation -->
            <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                <li class="nav-item" role="presentation"><button class="nav-link active" id="pills-profile-tab" data-bs-toggle="pill" data-bs-target="#pills-profile" type="button">Update Profile</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="pills-password-tab" data-bs-toggle="pill" data-bs-target="#pills-password" type="button">Change Password</button></li>
            </ul>

            <!-- Tab Content -->
            <div class="tab-content" id="pills-tabContent">
                <!-- Update Profile Tab -->
                <div class="tab-pane fade show active" id="pills-profile" role="tabpanel">
                    <form action="profile.php" method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                        <input type="hidden" name="action" value="update_profile">
                        <div class="row">
                            <div class="col-md-6 mb-3"><label for="first_name" class="form-label">First Name</label><input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($admin_user['first_name']); ?>" required></div>
                            <div class="col-md-6 mb-3"><label for="last_name" class="form-label">Last Name</label><input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($admin_user['last_name']); ?>" required></div>
                        </div>
                        <div class="mb-3"><label for="email" class="form-label">Email Address</label><input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($admin_user['email']); ?>" required></div>
                        <div class="mb-3"><label class="form-label">Username</label><input type="text" class="form-control" value="<?php echo htmlspecialchars($admin_user['username']); ?>" disabled readonly><small class="form-text text-muted">Username cannot be changed.</small></div>
                        <button type="submit" class="btn btn-primary">Save Profile</button>
                    </form>
                </div>

                <!-- Change Password Tab -->
                <div class="tab-pane fade" id="pills-password" role="tabpanel">
                    <form action="profile.php" method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                        <input type="hidden" name="action" value="change_password">
                        <div class="mb-3"><label for="current_password" class="form-label">Current Password</label><input type="password" class="form-control" id="current_password" name="current_password" required></div>
                        <div class="mb-3"><label for="new_password" class="form-label">New Password</label><input type="password" class="form-control" id="new_password" name="new_password" required></div>
                        <div class="mb-3"><label for="confirm_password" class="form-label">Confirm New Password</label><input type="password" class="form-control" id="confirm_password" name="confirm_password" required></div>
                        <button type="submit" class="btn btn-primary">Change Password</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
include 'includes/footer.php';
?>
