<?php
session_start();

// Redirect to login if session data is missing
if (empty($_SESSION['username']) || empty($_SESSION['userid']) || empty($_SESSION['database'])) {
    header("Location: login.html");
    exit();
}

$message = '';
$success = false; 

// If the form is submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $oldPassword = $_POST['old_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    // Basic validation: All fields are required
    if (empty(trim($oldPassword)) || empty(trim($newPassword)) || empty(trim($confirmPassword))) {
        $message = "All fields are required.";
    }
    // Confirm new password match
    elseif ($newPassword !== $confirmPassword) {
        $message = "Password and confirm password do not match.";
    }
    // Password length check
    elseif (strlen($newPassword) < 8) {
        $message = "Password must be at least 8 characters.";
    }
    // Check for password complexity: uppercase, lowercase, digit, special char
    elseif (
        !preg_match('/[A-Z]/', $newPassword) ||  // Uppercase
        !preg_match('/[a-z]/', $newPassword) ||  // Lowercase
        !preg_match('/[0-9]/', $newPassword) ||  // Digit
        !preg_match('/[\W]/', $newPassword)      // Special character
    ) {
        $message = "Password must include uppercase, lowercase, number, and special character.";
    } else {

        $username = $_SESSION['username'];
        $userid = $_SESSION['userid'];

        try {
            // Connect to SQL Server using PDO
            require_once 'connection.php';

            // Fetch current password hash
            $stmt = $pdo->prepare("SELECT PASSWORD FROM USERS WHERE USERNAME = :username");
            $stmt->bindParam(':username', $username);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            // Verify old password
            if ($row && password_verify($oldPassword, $row['PASSWORD'])) {
                // Hash the new password
                $newHashed = password_hash($newPassword, PASSWORD_BCRYPT);

                // Update password in DB
                $updateStmt = $pdo->prepare("UPDATE USERS SET PASSWORD = :newPassword WHERE USERNAME = :username AND USERID = :userid");
                $updateStmt->bindParam(':newPassword', $newHashed);
                $updateStmt->bindParam(':username', $username);
                $updateStmt->bindParam(':userid', $userid);
                $updateStmt->execute();

                $message = "Password changed successfully.";
                $success = true;  // Set success flag for JS redirect
            } else {
                $message = "Incorrect old password.";
            }
        } catch (PDOException $e) {
            $message = "Database error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Change Password</title>
    <link rel="stylesheet" href="main.css">
</head>
<body class="change_password">
    <button onclick="history.back();" id="back-button">Go Back</button>
    <div class="container">
        <h2>Change Password</h2>
        <form method="POST">
            <div class="form-group">
                <label for="old_password">Old Password</label>
                <input type="password" id="old_password" name="old_password" required>
            </div>
            <div class="form-group">
                <label for="new_password">New Password</label>
                <input type="password" id="new_password" name="new_password" required>
            </div>
            <div class="form-group">
                <label for="confirm_password">Confirm New Password</label>
                <input type="password" id="confirm_password" name="confirm_password" required>
            </div>
            <input type="submit" value="Update Password">
        </form>

        <?php if ($message): ?>
            <div class="message <?= $success ? 'success' : '' ?>">
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>
    </div>

    <?php if ($success): ?>
        <script>
            // Redirect after 1 second if password changed successfully
            setTimeout(() => {
                window.location.href = "landing.php";
            }, 1000);
        </script>
    <?php endif; ?>
</body>
</html>
