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

// Import PHPMailer classes for confirmation email
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"));

// Ensure all payment details are present
if (empty($data->razorpay_payment_id) || empty($data->razorpay_order_id) || empty($data->razorpay_signature)) {
    sendResponse(400, 'error', 'Invalid payment details');
}

// 1. Verify the signature securely
$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.');
}

// 2. Safely extract the Total Amount (catches different variable names just in case)
$final_amount = 0;
if (isset($data->totalAmount)) {
    $final_amount = $data->totalAmount;
} elseif (isset($data->total_amount)) {
    $final_amount = $data->total_amount;
} elseif (isset($data->amount)) {
    $final_amount = $data->amount;
}

// Force it to be a float so MySQL accepts it properly
$final_amount = (float)$final_amount;


// 3. Save the booking to the database
$database = new Database();
$db = $database->getConnection();

try {
    $query = "INSERT INTO package_bookings (
        package_id, customer_name, customer_email, customer_phone, 
        travel_date, adults, children, special_requests, 
        total_amount, razorpay_order_id, razorpay_payment_id, razorpay_signature, 
        payment_status, status
    ) VALUES (
        :package_id, :name, :email, :phone, 
        :travel_date, :adults, :children, :special_requests, 
        :amount, :rzp_order_id, :rzp_payment_id, :rzp_signature, 
        'successful', 'confirmed'
    )";

    $stmt = $db->prepare($query);
    
    // Safely map values, defaulting children to 0 if not provided
    $children = isset($data->children) ? (int)$data->children : 0;
    $specialRequests = isset($data->message) ? $data->message : '';

    $stmt->execute([
        ':package_id'       => $data->packageId,
        ':name'             => $data->name,
        ':email'            => $data->email,
        ':phone'            => $data->phone,
        ':travel_date'      => $data->travelDate,
        ':adults'           => $data->paxCount,
        ':children'         => $children,
        ':special_requests' => $specialRequests,
        ':amount'           => $final_amount, // <-- Now strictly uses the forced float value
        ':rzp_order_id'     => $data->razorpay_order_id,
        ':rzp_payment_id'   => $data->razorpay_payment_id,
        ':rzp_signature'    => $data->razorpay_signature
    ]);

    $bookingId = $db->lastInsertId();

    // 4. (Optional) Send a Confirmation Email to the Customer
    $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');
        $mail->addAddress($data->email, $data->name);
        $mail->addBCC(SMTP_FROM_EMAIL); // Admin copy

        $mail->isHTML(true);
        $mail->Subject = "Booking Confirmed - HR Trips";
        $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;'>Payment Successful!</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.
                </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</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>Payment ID:</strong> {$data->razorpay_payment_id}</li>
                        <li style='margin-bottom: 8px;'><strong>Amount Paid:</strong> ₹" . number_format($final_amount, 2) . "</li>
                        <li style='margin-bottom: 8px;'><strong>Travel Date:</strong> " . date('d M Y', strtotime($data->travelDate)) . "</li>
                        <li style='margin-bottom: 0;'><strong>Travelers:</strong> {$data->paxCount} Adults</li>
                    </ul>
                </div>

                <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                    Our travel experts will contact you shortly with your complete itinerary and further instructions.
                </p>
            </div>
        </div>";

        $mail->send();
    } catch (Exception $e) {
        error_log("Payment confirmation email failed to send. Mailer Error: {$mail->ErrorInfo}");
    }

    sendResponse(200, 'success', 'Payment verified and booking confirmed successfully');

} catch (PDOException $e) {
    error_log("CRITICAL: Payment successful but DB insert failed. Error: " . $e->getMessage());
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>