<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header("Location: index.php");
    exit();
}
$users_file = 'data/users.json';
$users = json_decode(file_get_contents($users_file), true);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current = md5($_POST['current']);
    $new = md5($_POST['new']);
    $confirm = md5($_POST['confirm']);

    if ($users[$_SESSION['admin']]['password'] !== $current) {
        $message = "Current password incorrect.";
    } elseif ($new !== $confirm) {
        $message = "New passwords do not match.";
    } else {
        $users[$_SESSION['admin']]['password'] = $new;
        file_put_contents($users_file, json_encode($users, JSON_PRETTY_PRINT));
        $message = "Password changed successfully.";
    }
}
?>
<!DOCTYPE html>
<html>
<head><title>Change Password</title></head>
<style>
    * {
        box-sizing: border-box;
    }
    body {
        font-family: Arial, sans-serif;
        background: #f2f2f2;
        margin: 0;
        padding: 0;
    }
    .container {
        max-width: 400px;
        margin: 40px auto;
        background: #fff;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    h2 {
        text-align: center;
        color: #333;
    }
    form {
        margin-top: 20px;
    }
    input[type="password"] {
        width: 100%;
        padding: 10px;
        margin: 8px 0;
        border: 1px solid #ccc;
        border-radius: 5px;
    }
    input[type="submit"] {
        width: 100%;
        padding: 10px;
        background: #28a745;
        color: white;
        border: none;
        border-radius: 5px;
        font-size: 16px;
        cursor: pointer;
    }
    input[type="submit"]:hover {
        background: #218838;
    }
    a {
        display: block;
        text-align: center;
        margin-bottom: 10px;
        text-decoration: none;
        color: #007bff;
    }
    a:hover {
        text-decoration: underline;
    }
    p {
        text-align: center;
        margin-top: 15px;
        font-weight: bold;
        color: #555;
    }

    @media screen and (max-width: 480px) {
        .container {
            margin: 20px;
            padding: 15px;
        }
    }
</style>

<body>
<h2>Change Password</h2>
<a href="dashboard.php">Back to Dashboard</a><br><br>
<form method="POST">
    Current Password: <input type="password" name="current"><br>
    New Password: <input type="password" name="new"><br>
    Confirm New Password: <input type="password" name="confirm"><br>
    <input type="submit" value="Change Password">
</form>
<?php if (isset($message)) echo "<p>$message</p>"; ?>
</body>
</html>
