<?php
require_once '../config/headers.php';
require_once '../config/constants.php'; // Required for SMTP settings
require_once '../config/database.php';
require_once '../utils/response.php';

// Import PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer files
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"));

// Basic validation
if (empty($data->package_id) || empty($data->customer_name) || empty($data->customer_email) || empty($data->customer_phone) || empty($data->travel_date)) {
    sendResponse(400, 'error', 'Missing required fields');
}

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

try {
    // 1. Fetch the Package Title (To use in the email)
    $pkgQuery = "SELECT title FROM holiday_packages WHERE id = :id LIMIT 1";
    $pkgStmt = $db->prepare($pkgQuery);
    $pkgStmt->execute([':id' => $data->package_id]);
    $packageTitle = "Holiday Package";
    if ($pkgStmt->rowCount() > 0) {
        $packageRow = $pkgStmt->fetch();
        $packageTitle = $packageRow['title'];
    }

    // 2. Insert the Booking into the Database
    $query = "INSERT INTO package_bookings 
              (package_id, customer_name, customer_email, customer_phone, travel_date, adults, children, special_requests) 
              VALUES (:package_id, :name, :email, :phone, :travel_date, :adults, :children, :requests)";
    
    $stmt = $db->prepare($query);
    
    $adults = isset($data->adults) ? (int)$data->adults : 1;
    $children = isset($data->children) ? (int)$data->children : 0;

    $stmt->execute([
        ':package_id' => $data->package_id,
        ':name' => $data->customer_name,
        ':email' => $data->customer_email,
        ':phone' => $data->customer_phone,
        ':travel_date' => $data->travel_date,
        ':adults' => $adults,
        ':children' => $children,
        ':requests' => $data->special_requests ?? null
    ]);

    $bookingId = $db->lastInsertId();

    // 3. Send the Confirmation Email using PHPMailer
    $emailSent = false;
    $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 Bookings');
        $mail->addAddress($data->customer_email, $data->customer_name);
        
        // Also send a copy to the Admin so you know a booking came in!
        $mail->addBCC(SMTP_FROM_EMAIL); 

        $mail->isHTML(true);
        $mail->Subject = "Booking Request Received - " . $packageTitle;
        
        // HTML Email Template
        $mail->Body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e2e8f0; border-radius: 10px; overflow: hidden;'>
            <div style='background-color: #0f172a; padding: 20px; text-align: center;'>
                <h1 style='color: #ffffff; margin: 0; font-size: 24px;'>Booking Request Received</h1>
            </div>
            <div style='padding: 30px; background-color: #ffffff;'>
                <p style='font-size: 16px; color: #334155;'>Hello <strong>{$data->customer_name}</strong>,</p>
                <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                    Thank you for choosing HR Trips! We have successfully received your booking request. 
                    Our travel desk is currently reviewing your details and checking availability.
                </p>
                
                <div style='background-color: #f8fafc; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #3b82f6;'>
                    <h3 style='margin-top: 0; color: #0f172a; font-size: 16px;'>Booking Details</h3>
                    <ul style='list-style-type: none; padding: 0; margin: 0; color: #475569; font-size: 14px;'>
                        <li style='margin-bottom: 8px;'><strong>Booking ID:</strong> #{$bookingId}</li>
                        <li style='margin-bottom: 8px;'><strong>Package:</strong> {$packageTitle}</li>
                        <li style='margin-bottom: 8px;'><strong>Travel Date:</strong> " . date('d M Y', strtotime($data->travel_date)) . "</li>
                        <li style='margin-bottom: 8px;'><strong>Travelers:</strong> {$adults} Adults" . ($children > 0 ? ", {$children} Children" : "") . "</li>
                        <li style='margin-bottom: 0;'><strong>Phone:</strong> {$data->customer_phone}</li>
                    </ul>
                </div>

                <div style='background-color: #fffbeb; padding: 15px; border: 1px dashed #f59e0b; border-radius: 8px; text-align: center; color: #b45309; font-weight: bold;'>
                    Status: PENDING CONFIRMATION
                </div>

                <p style='font-size: 14px; color: #64748b; line-height: 1.6; margin-top: 20px;'>
                    <strong>What happens next?</strong><br>
                    One of our travel experts will contact you shortly with the final confirmation and payment details to secure your reservation.
                </p>
                
                <hr style='border: none; border-top: 1px solid #e2e8f0; margin: 30px 0;'>
                <p style='font-size: 14px; color: #94a3b8; margin: 0;'>
                    Regards,<br>
                    <strong>The HR Trips Team</strong><br>
                    Call us: 7992481351
                </p>
            </div>
        </div>";

        $mail->send();
        $emailSent = true;
    } catch (Exception $e) {
        // We log the error but don't stop the script because the database insert was successful
        error_log("Booking Email failed to send. Mailer Error: {$mail->ErrorInfo}");
    }

    // 4. Return Success Response
    sendResponse(201, 'success', 'Booking request submitted successfully. ' . ($emailSent ? 'Confirmation email sent.' : 'Email failed to send.'));

} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>