<?php
/**
 * ===================================================================================
 * Admin Account Settings Page (Corrected)
 * ===================================================================================
 *
 * File: account_settings.php
 * Location: /homework_portal/admin/account_settings.php
 *
 * Purpose:
 * 1. Provides a secure form for the logged-in Super Admin to change their password.
 * 2. Correctly verifies the current password and saves the new password hash.
 */

require_once '../config.php';

// --- Security Check ---
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$admin_id = $_SESSION['admin_id'];
$errors = [];
$success_message = '';

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validation
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $errors[] = "All password fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $errors[] = "The new passwords do not match.";
    } elseif (strlen($new_password) < 8) {
        $errors[] = "New password must be at least 8 characters long.";
    } else {
        try {
            // Verify the current password
            $stmt = $pdo->prepare("SELECT password_hash FROM super_admins WHERE id = ?");
            $stmt->execute([$admin_id]);
            $admin = $stmt->fetch();

            if ($admin && password_verify($current_password, $admin['password_hash'])) {
                // If correct, hash and update the new password
                $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                
                // **FIX**: Correctly prepare the SQL and parameters for the update.
                $update_sql = "UPDATE super_admins SET password_hash = ? WHERE id = ?";
                $update_stmt = $pdo->prepare($update_sql);
                $update_stmt->execute([$new_password_hash, $admin_id]); // Use the correct variables
                
                $success_message = "Your password has been updated successfully!";
            } else {
                $errors[] = "The 'Current Password' you entered is incorrect.";
            }
        } catch (PDOException $e) {
            $errors[] = "Database error. Could not update password.";
            // error_log($e->getMessage());
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Account Settings - Admin Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
    </style>
</head>
<body class="min-h-screen">
    <div class="max-w-2xl mx-auto py-10">
        <div class="mb-4">
            <a href="dashboard.php" class="flex items-center text-blue-600 hover:text-blue-800 font-medium">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                Back to Dashboard
            </a>
        </div>
        <div class="bg-white p-8 rounded-lg shadow-lg">
            <h1 class="text-2xl font-bold text-gray-800 mb-6 font-brand">Change Admin Password</h1>

            <?php if ($success_message): ?><div class="p-4 mb-4 text-sm text-green-800 bg-green-100 rounded-lg"><?php echo e($success_message); ?></div><?php endif; ?>
            <?php if (!empty($errors)): ?><div class="p-4 mb-4 text-sm text-red-800 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach ($errors as $error) echo "<li>" . e($error) . "</li>"; ?></ul></div><?php endif; ?>

            <form action="account_settings.php" method="POST" class="space-y-6">
                <div>
                    <label for="current_password" class="block text-sm font-medium text-gray-700">Current Password</label>
                    <input type="password" name="current_password" id="current_password" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm" required>
                </div>
                <div>
                    <label for="new_password" class="block text-sm font-medium text-gray-700">New Password</label>
                    <input type="password" name="new_password" id="new_password" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm" required>
                </div>
                <div>
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700">Confirm New Password</label>
                    <input type="password" name="confirm_password" id="confirm_password" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm" required>
                </div>
                <div class="flex justify-end pt-4 border-t">
                    <a href="dashboard.php" class="px-6 py-2 text-gray-600 font-medium rounded-lg hover:bg-gray-100 mr-4">Cancel</a>
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow hover:bg-blue-700">Update Password</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
