<?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\Exception;
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, owner_name FROM hotel_registrations WHERE email = :email LIMIT 1");
    $stmt->execute([':email' => $data->email]);
    
    if ($stmt->rowCount() > 0) {
        $hotel = $stmt->fetch();
        
        // Generate 6-digit OTP and set expiry to 15 mins from now
        $otp = sprintf("%06d", mt_rand(1, 999999));
        $expiry = date("Y-m-d H:i:s", strtotime('+15 minutes'));

        // Update DB with OTP
        $updateStmt = $db->prepare("UPDATE hotel_registrations SET reset_otp = :otp, otp_expires_at = :expiry WHERE id = :id");
        $updateStmt->execute([':otp' => $otp, ':expiry' => $expiry, ':id' => $hotel['id']]);

        // Send Email
        $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, 'HR Trips Support');
            $mail->addAddress($data->email, $hotel['owner_name']);

            $mail->isHTML(true);
            $mail->Subject = "Password Reset OTP - HR Trips";
            $mail->Body    = "
            <div style='font-family: Arial, sans-serif; padding: 20px;'>
                <h2>Password Reset Request</h2>
                <p>Hello {$hotel['owner_name']},</p>
                <p>We received a request to reset your Hotel Owner Dashboard password.</p>
                <div style='background: #f4f4f5; padding: 15px; font-size: 24px; font-weight: bold; letter-spacing: 5px; text-align: center; margin: 20px 0;'>
                    {$otp}
                </div>
                <p>This OTP is valid for 15 minutes. Do not share it with anyone.</p>
                <p>If you did not request this, please ignore this email.</p>
            </div>";

            $mail->send();
        } catch (Exception $e) {
            sendResponse(500, 'error', 'Failed to send OTP email.');
        }
    }

    // Always return success even if email not found to prevent email enumeration attacks
    sendResponse(200, 'success', 'If the email exists, an OTP has been sent.');

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