<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include __DIR__ . '/../inc/db.php';
require_once __DIR__ . '/../TCPDF/tcpdf.php';

function indian_number_format($num, $decimals = 2) {
    $exploded = explode(".", number_format($num, $decimals, ".", ""));
    $whole = $exploded[0];
    $decimal = isset($exploded[1]) ? $exploded[1] : '';

    $last3 = substr($whole, -3);
    $rest = substr($whole, 0, -3);
    if ($rest != '') {
        $rest = preg_replace("/\B(?=(\d{2})+(?!\d))/", ",", $rest);
        $whole = $rest . "," . $last3;
    }

    return $decimal ? $whole . "." . $decimal : $whole;
}

class BookingOrderPDF extends TCPDF {
    public $booking_no;
    public $booking_date;

    public function Header() {
        $this->Image(__DIR__.'/../assets/img/logo.png', 10, 8, 50);
        $this->SetFont('helvetica', '', 8);
        $this->SetXY(140, 8);
        $this->MultiCell(60, 5, 
            "GST No: 27ABCDE1234F1Z5\nMobile: +91 98255 59080\nEmail: mytreasuretrip@gmail.com", 
            0, 'R', false);
        $this->SetDrawColor(12, 69, 110);
        $this->SetLineWidth(0.6);
        $this->Line(10, 30, 200, 30);
        $this->SetY(32);
        $this->SetFont('helvetica', 'B', 14);
        $this->SetTextColor(10, 69, 110);
        $this->Cell(0, 8, 'Booking Order', 0, 1, 'C');
        $this->SetTextColor(0, 0, 0);
        $currentY = $this->GetY();
        $this->Line(10, $currentY + 2, 200, $currentY + 2);
    }

    public function Footer() {
        $this->SetY(-20);
        $this->SetDrawColor(12, 69, 110);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->Ln(2);
        $this->SetFont('helvetica', '', 8);
        $this->MultiCell(0, 5, 
            "17, Suman Sajni Society, Near Jayant Park, Ghodasar, Ahmedabad, Gujarat, India.\nMobile: +91 98255 59080 | Email: mytreasuretrip@gmail.com | GST No: 27ABCDE1234F1Z5", 
            0, 'C', false);
    }

    public function addSectionTitle($title) {
        if ($this->GetY() > 250) $this->AddPage();
        $this->Ln(2);
        $this->SetFont('helvetica', 'B', 12);
        $this->SetFillColor(12, 69, 110);
        $this->SetTextColor(255, 255, 255);
        $this->Cell(0, 8, "  " . strtoupper($title), 0, 1, 'L', true);
        $this->Ln(2);
        $this->SetTextColor(0, 0, 0);
    }

    public function customerAndBookingDetails($booking) {
        $this->SetFont('dejavusans', '', 10);
        $startX = $this->GetX();
        $startY = $this->GetY();
        $cellHeight = 30;
        $leftWidth = 115;
        $rightWidth = 70;
        $gap = 5;
        $radius = 3;

        $this->SetFillColor(240, 248, 255);
        $this->SetDrawColor(180, 180, 180);

        $customerText = 
            "Customer Name: " . ucwords(strtolower($booking['customer_name'])) . "\n" .
            "Address: " . ucwords(strtolower($booking['customer_address'])) . "\n\n" .
            "Email: " . $booking['customer_email'] . "\n" .
            "Phone: " . $booking['customer_phone'];

        $this->RoundedRect($startX, $startY, $leftWidth, $cellHeight, $radius, '1111', 'DF');
        $this->SetXY($startX + 2, $startY + 2);
        $this->MultiCell($leftWidth - 4, 5, $customerText, 0, 'L', false);

        $bookingText = 
            "Booking No: " . $booking['booking_no'] . "\n" .
            "Booking Date: " . date('d-m-Y', strtotime($booking['booking_date'])) . "\n\n" .
            "Travel Date: " . date('d-m-Y', strtotime($booking['travel_date'])) . "\n" .
            "Destination: " . ucwords(strtolower($booking['destination']));

        $this->RoundedRect($startX + $leftWidth + $gap, $startY, $rightWidth, $cellHeight, $radius, '1111', 'DF');
        $this->SetXY($startX + $leftWidth + $gap + 2, $startY + 2);
        $this->MultiCell($rightWidth - 4, 5, $bookingText, 0, 'L', false);
        $this->Ln(10);
    }

    public function packageDetails($booking) {
        $this->addSectionTitle('Package & Travel Details');
        $this->SetFont('dejavusans', '', 10);

        $this->writeHTML('
            <table border="0.5" cellpadding="6" cellspacing="0" width="100%">
                <tr style="background-color:#f0f8ff;">
                    <td width="40%"><b>Package Name</b></td><td width="60%">' . ucwords(strtolower($booking['package_name'])) . '</td>
                </tr>
                <tr>
                    <td><b>No. of Nights</b></td><td>' . $booking['nights'] . '</td>
                </tr>
                <tr>
                    <td><b>Guests (Adult/Child)</b></td><td>' . $booking['adults'] . ' Adults / ' . $booking['child'] . ' Child</td>
                </tr>
                <tr>
                    <td><b>Extra Bed</b></td><td>' . $booking['extrabed'] . '</td>
                </tr>
                <tr>
                    <td><b>Total Rooms</b></td><td>' . $booking['rooms'] . '</td>
                </tr>
            </table>
        ', true, false, false, false, '');
    }

    public function hotelDetails($bookingId) {
    $this->addSectionTitle('Hotel Details');
    $this->SetFont('dejavusans', '', 10);
    global $conn;

    $bookingId = intval($bookingId); // Prevent SQL injection (assuming it's numeric)
    $query = "SELECT * FROM package_booking_hotels WHERE booking_id = $bookingId";
    $result = $conn->query($query);

    if (!$result) {
        // Output error message or log it
        $this->writeHTML("<p><strong>Error:</strong> " . $conn->error . "</p>", true, false, false, false, '');
        return;
    }

    if ($result->num_rows === 0) {
        $this->writeHTML("<p>No hotel details found for this booking.</p>", true, false, false, false, '');
        return;
    }

    $html = '<table border="1" cellpadding="5" cellspacing="0">
                <thead style="background-color:#0c456e; color:#ffffff;">
                    <tr>
                        <th width="40%">Hotel Name</th>
                        <th width="20%" align="center">Rooms</th>
                        <th width="20%" align="center">Hotel Type</th>
                        <th width="20%" align="center">Meal Plan</th>
                    </tr>
                </thead><tbody>';

    while ($row = $result->fetch_assoc()) {
        // Convert hotel type
        $hotelType = strtolower($row['hotel_type']);
        if (strpos($hotelType, '3') !== false) {
            $hotelType = '3*';
        } elseif (strpos($hotelType, '4') !== false) {
            $hotelType = '4*';
        } elseif (strpos($hotelType, '5') !== false) {
            $hotelType = '5*';
        } else {
            $hotelType = ucwords($hotelType); // fallback
        }

        $html .= '<tr>
                    <td width="40%">' . ucwords(strtolower($row['hotel_name'])) . ' (' . ucwords(strtolower($row['hotel_location'])) . ')</td>
                    <td width="20%" align="center">' . $row['hotel_rooms'] . '</td>
                    <td width="20%" align="center">' . $hotelType . '</td>
                    <td width="20%" align="center">' . strtoupper($row['meal_plan']) . '</td>
                </tr>';
    }

    $html .= '</tbody></table>';
    $this->writeHTML($html, true, false, false, false, '');
}



    public function pricingDetails($booking) {
        $this->addSectionTitle('Pricing Details');
        $this->SetFont('dejavusans', '', 10);

        $adult_total = $booking['adult_price'] * $booking['adults'];
        $child_total = $booking['child_price'] * $booking['child'];
        $extrabed_total = $booking['extra_bed_price'] * $booking['extrabed'];
        $subtotal = $adult_total + $child_total + $extrabed_total;

        $discount_amt = ($booking['discount'] / 100) * $subtotal;
        $subtotal_after_discount = $subtotal - $discount_amt;

        $gst_amt = 0;
        if ($booking['gst_included'] === 'yes') {
            $gst_amt = ($booking['gst_rate'] / 100) * $subtotal_after_discount;
        }

        $transport_amt = !empty($booking['transport_charges']) ? $booking['transport_charges'] : 0;
        $grand_total = $subtotal_after_discount + $gst_amt + $transport_amt;

        $html = '<table border="1" cellpadding="5" cellspacing="0">
            <tr><td><b>Adult Price (' . $booking['adults'] . ' × ₹' . indian_number_format($booking['adult_price']) . ')</b></td><td>₹' . indian_number_format($adult_total) . '</td></tr>';

        if ($booking['child'] > 0) {
            $html .= '<tr><td><b>Child Price (' . $booking['child'] . ' × ₹' . indian_number_format($booking['child_price']) . ')</b></td><td>₹' . indian_number_format($child_total) . '</td></tr>';
        }

        if ($booking['extrabed'] > 0) {
            $html .= '<tr><td><b>Extra Bed Price (' . $booking['extrabed'] . ' × ₹' . indian_number_format($booking['extra_bed_price']) . ')</b></td><td>₹' . indian_number_format($extrabed_total) . '</td></tr>';
        }

        $html .= '<tr><td><b>Subtotal</b></td><td>₹' . indian_number_format($subtotal) . '</td></tr>
                  <tr><td><b>Discount (' . $booking['discount'] . '%)</b></td><td>-₹' . indian_number_format($discount_amt) . '</td></tr>
                  <tr><td><b>Subtotal After Discount</b></td><td>₹' . indian_number_format($subtotal_after_discount) . '</td></tr>
                  <tr><td><b>GST (' . $booking['gst_rate'] . '%)</b></td><td>₹' . indian_number_format($gst_amt) . '</td></tr>
                  <tr><td><b>Transport Charges</b></td><td>₹' . indian_number_format($transport_amt) . '</td></tr>
                  <tr><td><b>Grand Total</b></td><td><b>₹' . indian_number_format($grand_total) . '</b></td></tr>';

        $html .= '</table>';
        $this->writeHTML($html, true, false, false, false, '');
    }
}

// --- Fetch and Create PDF ---
$booking_id = $_GET['id'];
$query = "SELECT pb.*, c.name AS customer_name, c.email AS customer_email, c.phone AS customer_phone, c.address AS customer_address 
          FROM package_bookings pb 
          LEFT JOIN customers c ON pb.customer_id = c.id 
          WHERE pb.id = $booking_id";
$result = $conn->query($query);
$booking = $result->fetch_assoc();

$pdf = new BookingOrderPDF();
$pdf->SetMargins(10, 50, 10);
$pdf->SetAutoPageBreak(true, 25);
$pdf->AddPage();
$pdf->customerAndBookingDetails($booking);
$pdf->packageDetails($booking);
$pdf->hotelDetails($booking_id);
$pdf->pricingDetails($booking);
$pdf->Output('booking_' . $booking['booking_no'] . '.pdf', 'I');
