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

// 1. Include your existing config and email function
require_once("../../includes/config.php"); 
require_once("../../includes/sendEmailOTP.php"); 

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

// 2. Check if user is actually logged in via session
if (isset($_SESSION['admin_id'])) {
    
    // Get the current password sent from the JS
    $current_password = $_POST['old_password'] ?? '';

    if (empty($current_password)) {
        echo json_encode(['status' => 'error', 'message' => 'Current password is required to send OTP.']);
        exit;
    }

    try {
        // 3. Verify the password against the database
        $stmt = $pdo->prepare("SELECT password, email FROM admin_account WHERE id = ? LIMIT 1");
        $stmt->execute([$_SESSION['admin_id']]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($admin && password_verify($current_password, $admin['password'])) {
            
            // 4. Password is correct! Generate OTP
            $otp = (string)rand(100000, 999999);
            
            // Store OTP in session for the final update step
            $_SESSION['update_otp'] = $otp;
            $_SESSION['update_otp_expiry'] = time() + (10 * 60); // 10 mins

            // 5. Send the email
            if (sendEmailOTP($admin['email'], $otp)) {
                $response = [
                    'status' => 'success', 
                    'message' => 'Verification code sent to ' . $admin['email']
                ];
            } else {
                $response = ['status' => 'error', 'message' => 'Failed to send email. Check SMTP settings.'];
            }
        } else {
            $response = ['status' => 'error', 'message' => 'Current password incorrect. OTP not sent.'];
        }
    } catch (PDOException $e) {
        $response = ['status' => 'error', 'message' => 'Database error.'];
    }
}

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