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

// 1. Include dependencies
require_once("../../includes/config.php"); 
require_once("../../includes/sendEmailOTP.php"); 

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');

    if (empty($email)) {
        echo json_encode(['status' => 'error', 'message' => 'Please enter your email address.']);
        exit;
    }

    try {
        // 2. Check if the email exists in your admin table
        $stmt = $pdo->prepare("SELECT id, username FROM admin_account WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $admin = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($admin) {
            // 3. Generate a secure 6-digit OTP
            $otp = (string)rand(100000, 999999);
            
            // 4. Store crucial reset data in SESSION
            // We store the email so the next API knows which user to update
            $_SESSION['reset_email'] = $email;
            $_SESSION['reset_otp'] = $otp;
            $_SESSION['reset_otp_expiry'] = time() + (15 * 60); // 15 minute window

            // 5. Send the email via your SMTP function
            // You can customize the subject to make it look professional
            $subject = "Password Reset Code - Admin Panel";
            if (sendEmailOTP($email, $otp)) {
                $response = [
                    'status' => 'success', 
                    'message' => 'A verification code has been sent to ' . $email
                ];
            } else {
                $response = ['status' => 'error', 'message' => 'Email could not be sent. Please check SMTP settings.'];
            }
        } else {
            // Security Tip: In public apps, we usually say "If email exists, a code was sent" 
            // to prevent email harvesting. For an Admin Panel, being specific is usually okay.
            $response = ['status' => 'error', 'message' => 'This email is not registered in our system.'];
        }

    } catch (PDOException $e) {
        $response = ['status' => 'error', 'message' => 'Database error occurred.'];
    }
}

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