<?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->razorpay_payment_id) || empty($data->razorpay_signature)) {
    sendResponse(400, 'error', 'Invalid payment details');
}

// 1. Verify Razorpay Signature
$generated_signature = hash_hmac('sha256', $data->razorpay_order_id . "|" . $data->razorpay_payment_id, RZP_KEY_SECRET);

if (!hash_equals($generated_signature, $data->razorpay_signature)) {
    sendResponse(400, 'error', 'Payment verification failed. Signature mismatch.');
}

$final_amount = isset($data->totalAmount) ? (float)$data->totalAmount : 0;

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

try {
    // 2. Insert into hotel_bookings
    $query = "INSERT INTO hotel_bookings (
        hotel_id, room_category, rooms_booked, adults, children, 
        checkin_date, checkout_date, customer_name, customer_email, customer_phone, 
        special_requests, total_amount, razorpay_order_id, razorpay_payment_id, 
        razorpay_signature, payment_status, booking_status
    ) VALUES (
        :hotel_id, :category, :rooms, :adults, :children, 
        :checkin, :checkout, :name, :email, :phone, 
        :requests, :amount, :rzp_order, :rzp_payment, 
        :rzp_sig, 'successful', 'confirmed'
    )";

    $stmt = $db->prepare($query);
    $stmt->execute([
        ':hotel_id' => $data->hotelId,
        ':category' => $data->roomType,
        ':rooms'    => (int)$data->rooms,
        ':adults'   => (int)$data->adults,
        ':children' => isset($data->children) ? (int)$data->children : 0,
        ':checkin'  => $data->checkin,
        ':checkout' => $data->checkout,
        ':name'     => $data->name,
        ':email'    => $data->email,
        ':phone'    => $data->phone,
        ':requests' => isset($data->specialRequests) ? $data->specialRequests : '',
        ':amount'   => $final_amount,
        ':rzp_order'=> $data->razorpay_order_id,
        ':rzp_payment'=>$data->razorpay_payment_id,
        ':rzp_sig'  => $data->razorpay_signature
    ]);

    // Get the newly created Booking ID
    $bookingId = $db->lastInsertId();

    // 3. Send Confirmation 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; // or ENCRYPTION_STARTTLS depending on your port         
        $mail->Port       = SMTP_PORT;                                    

        $mail->setFrom(SMTP_FROM_EMAIL, 'HR Trips Bookings');
        $mail->addAddress($data->email, $data->name);

        $mail->isHTML(true);
        $mail->Subject = "Hotel Booking Confirmed - HR Trips";
        
        // Format dates beautifully
        $checkinFormatted = date('d M Y', strtotime($data->checkin));
        $checkoutFormatted = date('d M Y', strtotime($data->checkout));
        $amountFormatted = number_format($final_amount, 2);

        $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: #10b981; padding: 20px; text-align: center;'>
                <h1 style='color: #ffffff; margin: 0; font-size: 24px;'>Hotel Booking Confirmed!</h1>
            </div>
            <div style='padding: 30px; background-color: #ffffff;'>
                <p style='font-size: 16px; color: #334155;'>Hello <strong>{$data->name}</strong>,</p>
                <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                    Thank you for booking with HR Trips. We have successfully received your payment and your hotel reservation is confirmed.
                </p>
                
                <div style='background-color: #f8fafc; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #10b981;'>
                    <h3 style='margin-top: 0; color: #0f172a; font-size: 16px;'>Booking Details (ID: #{$bookingId})</h3>
                    <ul style='list-style-type: none; padding: 0; margin: 0; color: #475569; font-size: 14px; line-height: 1.8;'>
                        <li><strong>Hotel:</strong> {$data->hotelName}</li>
                        <li><strong>Room:</strong> {$data->rooms}x {$data->roomType}</li>
                        <li><strong>Check-in:</strong> {$checkinFormatted}</li>
                        <li><strong>Check-out:</strong> {$checkoutFormatted}</li>
                        <li><strong>Guests:</strong> {$data->adults} Adults</li>
                        <li><strong>Amount Paid:</strong> ₹{$amountFormatted}</li>
                        <li><strong>Payment ID:</strong> {$data->razorpay_payment_id}</li>
                    </ul>
                </div>

                <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                    Please present this email along with a valid Government ID at the hotel reception during check-in.
                </p>
                <p style='font-size: 14px; color: #64748b; line-height: 1.6; margin-top: 20px;'>
                    Wishing you a wonderful stay!<br>
                    <strong>The HR Trips Team</strong>
                </p>
            </div>
        </div>";

        $mail->send();
    } catch (Exception $e) {
        // Log the error but don't fail the user request since payment and DB insert were successful
        error_log("Email failed to send. Mailer Error: {$mail->ErrorInfo}");
    }

    sendResponse(200, 'success', 'Booking confirmed successfully');
} catch (PDOException $e) {
    error_log("CRITICAL: Booking failed to insert after payment. Error: " . $e->getMessage());
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>