<?php
ob_start();
session_start();
header('Content-Type: application/json');

// 1. Include Database Configuration
require_once("../../includes/config.php"); 

$response = ['status' => 'error', 'message' => 'Invalid request'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get data from the Reset Form
    $user_otp = trim($_POST['otp'] ?? '');
    $new_pass = $_POST['new_password'] ?? '';
    
    // Get data from the Session (Set during the 'Send OTP' step)
    $email = $_SESSION['reset_email'] ?? '';
    $session_otp = $_SESSION['reset_otp'] ?? '';
    $expiry = $_SESSION['reset_otp_expiry'] ?? 0;

    try {
        // SECURITY CHECK 1: Ensure reset session exists
        if (empty($email) || empty($session_otp)) {
            throw new Exception("Session expired. Please start the process again.");
        }

        // SECURITY CHECK 2: Validate OTP Match
        if ($user_otp !== $session_otp) {
            throw new Exception("The verification code you entered is incorrect.");
        }

        // SECURITY CHECK 3: Check Expiry (Current time vs Expiry time)
        if (time() > $expiry) {
            throw new Exception("Verification code has expired. Please request a new one.");
        }

        // SECURITY CHECK 4: Password Complexity (8+ chars, 1 Upper, 1 Number, 1 Special)
        $regex = '/^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$/';
        if (!preg_match($regex, $new_pass)) {
            throw new Exception("Password must be 8+ characters and include uppercase, numbers, and symbols.");
        }

        // 2. Hash the new password for security
        $hashed_password = password_hash($new_pass, PASSWORD_DEFAULT);

        // 3. Update the Database
        $stmt = $pdo->prepare("UPDATE admin_account SET password = ? WHERE email = ?");
        $stmt->execute([$hashed_password, $email]);

        // 4. Success: Cleanup all reset sessions
        unset($_SESSION['reset_email']);
        unset($_SESSION['reset_otp']);
        unset($_SESSION['reset_otp_expiry']);
        unset($_SESSION['last_otp_sent']);

        $response = [
            'status' => 'success', 
            'message' => 'Password reset successful! You can now login with your new password.'
        ];

    } catch (Exception $e) {
        $response = ['status' => 'error', 'message' => $e->getMessage()];
    }
}

ob_clean();
echo json_encode($response);
exit;
?>