<?php
require_once __DIR__ . '/../includes/admin_auth.php';
require_once __DIR__ . '/../includes/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$admin_id = $_SESSION['admin_id'];
$error = '';
$success = '';

$conn = db();

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $old_password = trim($_POST['old_password'] ?? '');
    $new_password = trim($_POST['new_password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');

    if ($old_password === '' || $new_password === '' || $confirm_password === '') {
        $error = "All fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error = "New password and confirmation do not match.";
    } else {

        // Fetch current password hash
        $stmt = $conn->prepare("SELECT password FROM users WHERE id=? LIMIT 1");
        $stmt->bind_param("i", $admin_id);
        $stmt->execute();
        $stmt->bind_result($current_hash);
        $stmt->fetch();
        $stmt->close();

        if (!password_verify($old_password, $current_hash)) {
            $error = "Old password is incorrect.";
        } else {
            // Update password
            $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
            $stmt->bind_param("si", $new_hash, $admin_id);
            if ($stmt->execute()) {
                $success = "Password updated successfully.";
            } else {
                $error = "Database error. Please try again.";
            }
            $stmt->close();
        }
    }
}

ob_start();
?>

<div class="main-content">
    <h2>Change Password</h2>

    <?php if ($error): ?>
        <div style="padding:10px;background:#fee2e2;color:#b91c1c;border-radius:6px;margin-bottom:15px;">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php elseif ($success): ?>
        <div style="padding:10px;background:#d1fae5;color:#065f46;border-radius:6px;margin-bottom:15px;">
            <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>

    <form method="POST" style="max-width:400px;">
        <label>Old Password</label>
        <input type="password" name="old_password" required style="width:100%;padding:10px;margin-bottom:10px;">
        
        <label>New Password</label>
        <input type="password" name="new_password" required style="width:100%;padding:10px;margin-bottom:10px;">

        <label>Confirm New Password</label>
        <input type="password" name="confirm_password" required style="width:100%;padding:10px;margin-bottom:15px;">

        <button type="submit" style="padding:10px 20px;background:#1a73e8;color:white;border:none;border-radius:6px;cursor:pointer;">Update Password</button>
    </form>
</div>

<?php
$content = ob_get_clean();
$page_title = "Admin Change Password";
include '../components/admin_layout.php';
?>