<?php
require_once '../config/headers.php';
require_once '../config/constants.php'; // Required for SMTP & RAZORPAY 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"));

if (empty($data->id) || empty($data->status)) {
    sendResponse(400, 'error', 'Booking ID and status are required');
}

// Added 'completed' to valid statuses
$valid_statuses = ['pending', 'confirmed', 'cancelled', 'completed'];
if (!in_array($data->status, $valid_statuses)) {
    sendResponse(400, 'error', 'Invalid status value');
}

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

try {
    // 1. Fetch booking details to get the customer's email, payment, and package info
    $fetchQuery = "
        SELECT b.*, p.title as package_title 
        FROM package_bookings b 
        LEFT JOIN holiday_packages p ON b.package_id = p.id 
        WHERE b.id = :id LIMIT 1
    ";
    $fetchStmt = $db->prepare($fetchQuery);
    $fetchStmt->execute([':id' => $data->id]);
    
    if ($fetchStmt->rowCount() === 0) {
        sendResponse(404, 'error', 'Booking not found');
    }
    
    $booking = $fetchStmt->fetch(PDO::FETCH_ASSOC);

    // Prevent redundant updates
    if ($booking['status'] === $data->status) {
        sendResponse(200, 'success', 'Status is already ' . $data->status);
    }

    $refundNote = "";

    // 2. Process Razorpay Refund if status is changed to cancelled
    if ($data->status === 'cancelled' && !empty($booking['razorpay_payment_id'])) {
        $paymentId = $booking['razorpay_payment_id'];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.razorpay.com/v1/payments/{$paymentId}/refund");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([])); // Empty JSON array for full refund
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        // Make sure RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET are defined in constants.php
        curl_setopt($ch, CURLOPT_USERPWD, RZP_KEY_ID . ":" . RZP_KEY_SECRET);
        
        $refundResponse = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200) {
            $refundNote = " Refund initiated via Razorpay.";
        } else {
            error_log("Razorpay Refund Error for Payment ID $paymentId: " . $refundResponse);
            $refundNote = " Note: Automatic refund failed. Check Razorpay Dashboard.";
        }
    }

    // 3. Update the status in the database
    $updateQuery = "UPDATE package_bookings SET status = :status WHERE id = :id";
    $updateStmt = $db->prepare($updateQuery);
    $updateStmt->execute([
        ':status' => $data->status,
        ':id' => $data->id
    ]);

    // 4. Send Email if the new status requires notification
    $emailSent = false;
    
    if (in_array($data->status, ['confirmed', 'cancelled', 'completed'])) {
        $mail = new PHPMailer(true);

        try {
            // SMTP Settings
            $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($booking['customer_email'], $booking['customer_name']);

            $mail->isHTML(true);
            
            $packageTitle = $booking['package_title'] ?: "Holiday Package";

            // --- CONFIRMED EMAIL TEMPLATE ---
            if ($data->status === 'confirmed') {
                $mail->Subject = "Booking Confirmed! - " . $packageTitle;
                $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: #22c55e; padding: 20px; text-align: center;'>
                        <h1 style='color: #ffffff; margin: 0; font-size: 24px;'>Booking Confirmed! 🎉</h1>
                    </div>
                    <div style='padding: 30px; background-color: #ffffff;'>
                        <p style='font-size: 16px; color: #334155;'>Hello <strong>{$booking['customer_name']}</strong>,</p>
                        <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                            Great news! Your booking for <strong>{$packageTitle}</strong> has been officially confirmed by our team.
                        </p>
                        
                        <div style='background-color: #f8fafc; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #22c55e;'>
                            <ul style='list-style-type: none; padding: 0; margin: 0; color: #475569; font-size: 14px;'>
                                <li style='margin-bottom: 8px;'><strong>Booking ID:</strong> #{$booking['id']}</li>
                                <li style='margin-bottom: 8px;'><strong>Travel Date:</strong> " . date('d M Y', strtotime($booking['travel_date'])) . "</li>
                                <li style='margin-bottom: 0;'><strong>Travelers:</strong> {$booking['adults']} Adults" . ($booking['children'] > 0 ? ", {$booking['children']} Children" : "") . "</li>
                            </ul>
                        </div>
                        <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                            If you have any further questions or need assistance, please feel free to reply to this email or call us at <strong>7992481351</strong>.
                        </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></p>
                    </div>
                </div>";
            } 
            // --- CANCELLED EMAIL TEMPLATE ---
            else if ($data->status === 'cancelled') {
                $amountText = !empty($booking['total_amount']) ? "A full refund of <strong>₹" . number_format($booking['total_amount'], 2) . "</strong> has been initiated to your original payment method. It usually takes 5-7 business days to reflect in your account." : "";

                $mail->Subject = "Booking Cancelled & Refund Initiated - " . $packageTitle;
                $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: #ef4444; padding: 20px; text-align: center;'>
                        <h1 style='color: #ffffff; margin: 0; font-size: 24px;'>Booking Cancelled</h1>
                    </div>
                    <div style='padding: 30px; background-color: #ffffff;'>
                        <p style='font-size: 16px; color: #334155;'>Hello <strong>{$booking['customer_name']}</strong>,</p>
                        <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                            We regret to inform you that your booking request for <strong>{$packageTitle}</strong> (Booking ID: #{$booking['id']}) has been cancelled.
                        </p>
                        <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                            {$amountText}
                        </p>
                        <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                            If you believe this was a mistake, or if you would like to explore other travel dates or packages, please contact our support team.
                        </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>";
            }
            // --- COMPLETED EMAIL TEMPLATE ---
            else if ($data->status === 'completed') {
                $mail->Subject = "Thank You for Traveling With Us! - " . $packageTitle;
                $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: #3b82f6; padding: 20px; text-align: center;'>
                        <h1 style='color: #ffffff; margin: 0; font-size: 24px;'>Tour Completed! 🌟</h1>
                    </div>
                    <div style='padding: 30px; background-color: #ffffff;'>
                        <p style='font-size: 16px; color: #334155;'>Hello <strong>{$booking['customer_name']}</strong>,</p>
                        <p style='font-size: 15px; color: #475569; line-height: 1.6;'>
                            We hope you had a wonderful and memorable experience on your <strong>{$packageTitle}</strong> trip!
                        </p>
                        <p style='font-size: 14px; color: #64748b; line-height: 1.6;'>
                            Thank you for choosing HR Trips for your travel needs. We would love to hear your feedback and hope to see you again for your next adventure.
                        </p>
                        <hr style='border: none; border-top: 1px solid #e2e8f0; margin: 30px 0;'>
                        <p style='font-size: 14px; color: #94a3b8; margin: 0;'>Warm Regards,<br><strong>The HR Trips Team</strong></p>
                    </div>
                </div>";
            }

            $mail->send();
            $emailSent = true;
        } catch (Exception $e) {
            // Log error but don't fail the API request since the database update succeeded
            error_log("Status Update Email failed. Mailer Error: {$mail->ErrorInfo}");
        }
    }

    $responseMessage = 'Booking status updated successfully.';
    if (in_array($data->status, ['confirmed', 'cancelled', 'completed'])) {
        $responseMessage .= $emailSent ? ' Notification email sent.' : ' Note: Email delivery failed.';
    }
    
    // Append Razorpay note if applicable
    $responseMessage .= $refundNote;

    sendResponse(200, 'success', $responseMessage);

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