<?php
require_once '../config/headers.php';
require_once '../config/constants.php';
require_once '../config/database.php';
require_once '../utils/response.php';

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

// Load PHPMailer (Ensure paths point to the root phpmailer folder)
require '../phpmailer/src/Exception.php';
require '../phpmailer/src/PHPMailer.php';
require '../phpmailer/src/SMTP.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

$data = json_decode(file_get_contents("php://input"));

if (empty($data->email)) {
    sendResponse(400, 'error', 'Email is required');
}

$database = new Database();
$db = $database->getConnection();

try {
    $stmt = $db->prepare("SELECT id, first_name FROM admins WHERE email = :email LIMIT 1");
    $stmt->execute(['email' => $data->email]);

    if ($stmt->rowCount() > 0) {
        $admin = $stmt->fetch();
        
        $otp = sprintf("%06d", mt_rand(1, 999999));
        $expiresAt = date("Y-m-d H:i:s", strtotime('+15 minutes'));

        $updateStmt = $db->prepare("UPDATE admins SET reset_otp = :otp, otp_expires_at = :expires WHERE id = :id");
        $updateStmt->execute([
            'otp' => $otp,
            'expires' => $expiresAt,
            'id' => $admin['id']
        ]);

        // Send Email using PHPMailer
        $mail = new PHPMailer(true);
        
        try {
            $mail->isSMTP();                                            
            $mail->Host       = SMTP_HOST;                     
            $mail->SMTPAuth   = true;                                   
            $mail->Username   = SMTP_USER;                     
            $mail->Password   = SMTP_PASS;                               
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            
            $mail->Port       = SMTP_PORT;                                    

            $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
            $mail->addAddress($data->email, $admin['first_name']);

            $mail->isHTML(true);
            $mail->Subject = "HR Trips - Admin Password Reset OTP";
            
            $mail->Body = "
            <div style='font-family: Arial, sans-serif; max-width: 500px; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
                <h2 style='color: #333;'>Password Reset Request</h2>
                <p>Hello {$admin['first_name']},</p>
                <p>Your One Time Password (OTP) for the admin panel is:</p>
                <div style='background-color: #f4f4f4; padding: 15px; text-align: center; font-size: 24px; letter-spacing: 5px; font-weight: bold; color: #000; margin: 20px 0; border-radius: 5px;'>
                    {$otp}
                </div>
                <p style='color: #d9534f; font-size: 14px;'>This OTP will expire in 15 minutes.</p>
            </div>";

            $mail->send();
        } catch (Exception $e) {
            // Log error internally if needed, but don't stop the generic success message below
        }
    } 

    // Always return success to prevent email enumeration (guessing emails)
    sendResponse(200, 'success', 'If the email exists, a recovery link has been sent.');

} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error occurred');
}
?>