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

// 1. Load Database Connection
require_once("../../includes/config.php"); 

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

// 2. Ensure admin is logged in
if (isset($_SESSION['admin_id'])) {
    
    // Get form data
    $new_username = trim($_POST['username'] ?? '');
    $new_email    = trim($_POST['email'] ?? '');
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $user_otp     = $_POST['update_otp'] ?? '';

    try {
        // 3. VALIDATION: Check OTP first
        if (!isset($_SESSION['update_otp']) || $user_otp !== $_SESSION['update_otp']) {
            throw new Exception("Invalid or expired verification code.");
        }

        if (time() > $_SESSION['update_otp_expiry']) {
            throw new Exception("Verification code has expired. Please send a new one.");
        }

        // 4. NEW VALIDATION: Check Password Strength Requirements
        // If the user provided a new password, check: 8+ chars, 1 Upper, 1 Number, 1 Special
        if (!empty($new_password)) {
            $regex = '/^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$/';
            if (!preg_match($regex, $new_password)) {
                throw new Exception("New password must be at least 8 characters, include one uppercase letter, one number, and one special character.");
            }
        }

        // 5. VALIDATION: Verify current password again before saving changes
        $stmt = $pdo->prepare("SELECT password FROM admin_account WHERE id = ? LIMIT 1");
        $stmt->execute([$_SESSION['admin_id']]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$admin || !password_verify($old_password, $admin['password'])) {
            throw new Exception("Security check failed: Current password incorrect.");
        }

        // 6. UPDATE LOGIC
        if (!empty($new_password)) {
            // Case A: User wants to change EVERYTHING including password
            $hashed_pass = password_hash($new_password, PASSWORD_DEFAULT);
            $update_stmt = $pdo->prepare("UPDATE admin_account SET username = ?, email = ?, password = ? WHERE id = ?");
            $update_stmt->execute([$new_username, $new_email, $hashed_pass, $_SESSION['admin_id']]);
        } else {
            // Case B: User only changing username/email
            $update_stmt = $pdo->prepare("UPDATE admin_account SET username = ?, email = ? WHERE id = ?");
            $update_stmt->execute([$new_username, $new_email, $_SESSION['admin_id']]);
        }

        // 7. SUCCESS: Cleanup sessions and prepare response
        unset($_SESSION['update_otp']);
        unset($_SESSION['update_otp_expiry']);
        
        // Update the session username if it's used elsewhere in the site
        $_SESSION['admin_user'] = $new_username;

        $response = [
            'status' => 'success', 
            'message' => 'Profile updated successfully! Refreshing page...'
        ];

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

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