<?php
session_start();

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: index.php");
    exit();
}

$servername = "localhost";
$username = "dannygym_k-xprex";
$password = "Sasketchwan,1";
$dbname = "dannygym_ k-xprex";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Database connection failed.");
}

function clean_output($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function verify_admin_password($inputPassword, $storedPassword) {
    if (password_verify($inputPassword, $storedPassword)) {
        return true;
    }

    $passwordInfo = password_get_info($storedPassword);
    $isHashed = !empty($passwordInfo['algo']);

    if (!$isHashed && hash_equals($storedPassword, $inputPassword)) {
        return true;
    }

    return false;
}

$successMessage = "";
$errorMessage = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $currentPassword = trim($_POST["current_password"] ?? "");
    $newPassword = trim($_POST["new_password"] ?? "");
    $confirmPassword = trim($_POST["confirm_password"] ?? "");

    if ($currentPassword === "" || $newPassword === "" || $confirmPassword === "") {
        $errorMessage = "Please fill all password fields.";
    } elseif ($newPassword !== $confirmPassword) {
        $errorMessage = "New password and confirm password do not match.";
    } elseif (strlen($newPassword) < 8) {
        $errorMessage = "New password must be at least 8 characters long.";
    } else {
        $adminUsername = $_SESSION['admin_username'] ?? 'admin';

        $stmt = $conn->prepare("SELECT id, password FROM admin WHERE username = ? LIMIT 1");
        $stmt->bind_param("s", $adminUsername);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result && $result->num_rows === 1) {
            $admin = $result->fetch_assoc();

            if (verify_admin_password($currentPassword, $admin['password'])) {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

                $updateStmt = $conn->prepare("UPDATE admin SET password = ? WHERE id = ?");
                $updateStmt->bind_param("si", $hashedPassword, $admin['id']);

                if ($updateStmt->execute()) {
                    $successMessage = "Admin password changed successfully.";
                } else {
                    $errorMessage = "Unable to update password. Please try again.";
                }

                $updateStmt->close();
            } else {
                $errorMessage = "Current password is incorrect.";
            }
        } else {
            $errorMessage = "Admin account not found.";
        }

        $stmt->close();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Change Password - K-Express Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f4f7fb;
            color: #172033;
        }

        .admin-layout {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 260px;
            background: #071a3d;
            color: #fff;
            padding: 28px 20px;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
        }

        .brand {
            font-size: 23px;
            font-weight: 800;
            margin-bottom: 35px;
        }

        .brand span {
            color: #01ba7c;
        }

        .nav-link {
            display: block;
            color: #d7deea;
            text-decoration: none;
            padding: 13px 14px;
            border-radius: 10px;
            margin-bottom: 8px;
            font-size: 15px;
        }

        .nav-link:hover,
        .nav-link.active {
            background: #01ba7c;
            color: #fff;
        }

        .main-content {
            margin-left: 260px;
            width: calc(100% - 260px);
            padding: 32px;
        }

        .topbar {
            background: #fff;
            padding: 22px 24px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(7, 26, 61, 0.06);
            margin-bottom: 28px;
        }

        .topbar h1 {
            margin: 0;
            font-size: 25px;
            color: #071a3d;
        }

        .topbar p {
            margin: 6px 0 0;
            color: #647084;
            font-size: 14px;
        }

        .password-card {
            max-width: 560px;
            background: #fff;
            border-radius: 18px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(7, 26, 61, 0.06);
        }

        .password-card h2 {
            margin: 0 0 8px;
            color: #071a3d;
            font-size: 22px;
        }

        .password-card p {
            margin: 0 0 24px;
            color: #647084;
            line-height: 1.6;
        }

        .form-group {
            margin-bottom: 18px;
        }

        label {
            display: block;
            font-weight: 700;
            font-size: 14px;
            margin-bottom: 8px;
            color: #27344d;
        }

        input {
            width: 100%;
            padding: 14px 15px;
            border: 1px solid #dce3ee;
            border-radius: 12px;
            font-size: 15px;
            outline: none;
        }

        input:focus {
            border-color: #01ba7c;
            box-shadow: 0 0 0 4px rgba(1, 186, 124, 0.12);
        }

        .submit-btn {
            border: none;
            background: #01ba7c;
            color: #fff;
            padding: 14px 22px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 800;
            cursor: pointer;
            width: 100%;
            margin-top: 8px;
        }

        .submit-btn:hover {
            background: #019f69;
        }

        .alert {
            padding: 15px 16px;
            border-radius: 12px;
            font-weight: 700;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #e8fff6;
            color: #036b48;
            border: 1px solid #b7f2dc;
        }

        .alert-error {
            background: #fff1f1;
            color: #a72828;
            border: 1px solid #ffc8c8;
        }

        .note {
            margin-top: 18px;
            font-size: 13px;
            color: #647084;
            line-height: 1.6;
        }

        @media (max-width: 900px) {
            .sidebar {
                position: static;
                width: 100%;
                height: auto;
            }

            .admin-layout {
                display: block;
            }

            .main-content {
                margin-left: 0;
                width: 100%;
                padding: 20px;
            }
        }
    </style>
</head>

<body>

<div class="admin-layout">
    <aside class="sidebar">
        <div class="brand">K-<span>Express</span></div>

        <a href="dashboard.php" class="nav-link">Dashboard</a>
        <a href="create_client.php" class="nav-link">Create Client</a>
        <a href="update_location.php" class="nav-link">Update Location</a>
        <a href="view_clients.php" class="nav-link">View Clients</a>
        <a href="change_admin_password.php" class="nav-link active">Change Password</a>
        <a href="logout.php" class="nav-link">Logout</a>
    </aside>

    <main class="main-content">
        <div class="topbar">
            <h1>Change Admin Password</h1>
            <p>Update your admin login password securely.</p>
        </div>

        <div class="password-card">
            <h2>Password Security</h2>
            <p>Enter your current password, then choose a new password.</p>

            <?php if ($successMessage !== '') { ?>
                <div class="alert alert-success">
                    <?php echo clean_output($successMessage); ?>
                </div>
            <?php } ?>

            <?php if ($errorMessage !== '') { ?>
                <div class="alert alert-error">
                    <?php echo clean_output($errorMessage); ?>
                </div>
            <?php } ?>

            <form method="POST" action="">
                <div class="form-group">
                    <label for="current_password">Current Password</label>
                    <input 
                        type="password" 
                        id="current_password" 
                        name="current_password" 
                        required
                        autocomplete="current-password"
                    >
                </div>

                <div class="form-group">
                    <label for="new_password">New Password</label>
                    <input 
                        type="password" 
                        id="new_password" 
                        name="new_password" 
                        required
                        autocomplete="new-password"
                    >
                </div>

                <div class="form-group">
                    <label for="confirm_password">Confirm New Password</label>
                    <input 
                        type="password" 
                        id="confirm_password" 
                        name="confirm_password" 
                        required
                        autocomplete="new-password"
                    >
                </div>

                <button type="submit" class="submit-btn">Change Password</button>
            </form>

            <div class="note">
                Use at least 8 characters. After changing your password, use the new one for your next login.
            </div>
        </div>
    </main>
</div>

</body>
</html>