<?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->id)) {
    sendResponse(400, 'error', 'Booking ID is required');
}

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

try {
    // 1. Fetch booking details
    $stmt = $db->prepare("SELECT b.*, h.hotel_name FROM hotel_bookings b LEFT JOIN hotel_registrations h ON b.hotel_id = h.id WHERE b.id = :id LIMIT 1");
    $stmt->execute([':id' => $data->id]);
    $booking = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$booking) {
        sendResponse(404, 'error', 'Booking not found');
    }

    if ($booking['booking_status'] === 'cancelled') {
        sendResponse(400, 'error', 'Booking is already cancelled');
    }

    // 2. Process Razorpay Refund if payment was successful
    if ($booking['payment_status'] === 'successful' && !empty($booking['razorpay_payment_id'])) {
        $razorpay_payment_id = $booking['razorpay_payment_id'];
        $refund_amount = $booking['total_amount'] * 100; // Razorpay requires paise

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.razorpay.com/v1/payments/{$razorpay_payment_id}/refund");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['amount' => $refund_amount]));
        // Authenticate with Razorpay using Basic Auth
        curl_setopt($ch, CURLOPT_USERPWD, RZP_KEY_ID . ":" . RZP_KEY_SECRET);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        
        $result = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_status !== 200) {
            $error_data = json_decode($result, true);
            sendResponse(500, 'error', 'Razorpay Refund Failed: ' . ($error_data['error']['description'] ?? 'Unknown error'));
        }
    }

    // 3. Update Database Status
    $new_payment_status = ($booking['payment_status'] === 'successful') ? 'refunded' : $booking['payment_status'];
    $updateStmt = $db->prepare("UPDATE hotel_bookings SET booking_status = 'cancelled', payment_status = :p_status WHERE id = :id");
    $updateStmt->execute([':p_status' => $new_payment_status, ':id' => $data->id]);

    // 4. Send Cancellation 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 Bookings');
        $mail->addAddress($booking['customer_email'], $booking['customer_name']);

        $mail->isHTML(true);
        $mail->Subject = "Booking Cancelled & Refunded - 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: #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='color: #334155;'>Hello <strong>{$booking['customer_name']}</strong>,</p>
                <p style='color: #475569;'>Your booking at <strong>{$booking['hotel_name']}</strong> has been successfully cancelled.</p>
                " . (($booking['payment_status'] === 'successful') ? "<p style='color: #475569;'>A refund of <strong>₹" . number_format($booking['total_amount'], 2) . "</strong> has been initiated to your original payment method. It may take 5-7 business days to reflect in your account.</p>" : "") . "
                <p style='color: #64748b; font-size: 14px; margin-top: 20px;'>We hope to serve you again in the future.</p>
            </div>
        </div>";
        $mail->send();
    } catch (Exception $e) {
        error_log("Cancellation email failed: {$mail->ErrorInfo}");
    }

    sendResponse(200, 'success', 'Booking cancelled and refunded successfully');

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