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

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

// 2. Load PHPMailer Files (Manual Path)
require '../../phpmailer/Exception.php';
require '../../phpmailer/PHPMailer.php';
require '../../phpmailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Re-using the same Email Function
 */
function sendEmailOTP($recipientEmail, $otp) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'mushtaqueahmed178@gmail.com'; // Your Gmail
        $mail->Password   = 'irft pnqt hqiv ggtx';     // Your 16-char App Password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('mushtaqueahmed178@gmail.com', 'Admin Portal');
        $mail->addAddress($recipientEmail);

        $mail->isHTML(true);
        $mail->Subject = "Your New Login OTP: $otp";
        $mail->Body    = "Your new verification code is: <b>$otp</b>. It expires in 10 minutes.";
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        return false;
    }
}

// 3. Main Logic
$response = ['status' => 'error', 'message' => 'Session expired. Please login again.'];

if (isset($_SESSION['temp_admin_id'])) {
    try {
        // Fetch the email again based on the temporary session ID
        $stmt = $pdo->prepare("SELECT email FROM admin_account WHERE id = ? LIMIT 1");
        $stmt->execute([$_SESSION['temp_admin_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && !empty($user['email'])) {
            // Generate New OTP
            $newOtp = (string)rand(100000, 999999);
            
            // Update the Session with the NEW code
            $_SESSION['pending_otp'] = $newOtp;
            $_SESSION['otp_expiry']  = time() + (10 * 60);

            // Send the Email
            if (sendEmailOTP($user['email'], $newOtp)) {
                $response = ['status' => 'success', 'message' => 'New OTP sent!'];
            } else {
                $response = ['status' => 'error', 'message' => 'Failed to send email. Check SMTP settings.'];
            }
        } else {
            $response = ['status' => 'error', 'message' => 'Admin email not found in database.'];
        }
    } catch (PDOException $e) {
        $response = ['status' => 'error', 'message' => 'Database error.'];
    }
}

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