<?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] : '';

    // Start from last 3 digits
    $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 TravelQuotationPDF extends TCPDF {
    public $quotation_no;
    public $quotation_date;

    // Header
    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);

		// Print the title "Travel Quotation"
		$this->Cell(0, 8, 'Package Quotation', 0, 1, 'C'); // height = 8

		$this->SetTextColor(0, 0, 0);

		// Now get the current Y position
		$currentY = $this->GetY();

		// Draw the line very close to the text
		$this->Line(10, $currentY + 2, 200, $currentY + 2); // small 2pt gap only



    }

    // Footer
    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);
    }

    // Section Title
    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);
    }

   // Customer Details with Rounded Border (NO Shadow)
public function customerAndQuotationDetails($quotation) {
    $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);

    // Left box
    $customerText = 
        "Customer Name: " . ucwords(strtolower($quotation['customer_name'])) . "\n" .
        "Address: " . ucwords(strtolower($quotation['customer_address'])) . "\n\n" .
        "Email: " . $quotation['customer_email'] . "\n" .
        "Phone: " . $quotation['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);

    // Right box
    $quotationText = 
        "Quotation No: " . $quotation['quotation_no'] . "\n" .
        "Quotation Date: " . date('d-m-Y', strtotime($quotation['quotation_date'])) . "\n\n" .
        "Travel Date: " . date('d-m-Y', strtotime($quotation['travel_date'])) . "\n" .
        "Destination: " . ucwords(strtolower($quotation['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, $quotationText, 0, 'L', false);

    $this->Ln(15);
}

// Package Details
public function packageDetails($quotation) {
    $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($quotation['package_name'])) . '</td>
            </tr>
            <tr>
                <td><b>No. of Nights</b></td><td>' . $quotation['nights'] . '</td>
            </tr>
            <tr>
                <td><b>Guests (Adult/Child)</b></td><td>' . $quotation['adults'] . ' Adults / ' . $quotation['child'] . ' Child</td>
            </tr>
            <tr>
                <td><b>Extra Bed</b></td><td>' . $quotation['extrabed'] . '</td>
            </tr>
            <tr>
                <td><b>Total Rooms</b></td><td>' . $quotation['rooms'] . '</td>
            </tr>
        </table>
    ', true, false, false, false, '');
}


    // Hotel Details
   public function hotelDetails($quotationId) {
    $this->addSectionTitle('Hotel Details');
    $this->SetFont('dejavusans', '', 10);

    global $conn;
    $query = "SELECT * FROM quotation_hotels WHERE quotation_id = $quotationId";
    $result = $conn->query($query);

    $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($quotation) {
    $this->addSectionTitle('Pricing Details');
    $this->SetFont('dejavusans', '', 10);

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

    $subtotal = $adult_total + $child_total + $extrabed_total;

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

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

    // Transport
    $transport_amt = !empty($quotation['transport_charges']) ? $quotation['transport_charges'] : 0;

    // Final Grand Total
    $grand_total = $subtotal_after_discount + $gst_amt + $transport_amt;

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

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

if ($quotation['extrabed'] > 0) {
    $html .= '<tr><td><b>Extra Bed (' . $quotation['extrabed'] . ' × ₹' . indian_number_format($quotation['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>';

if ($quotation['discount'] > 0) {
    $html .= '<tr><td><b>Discount (' . $quotation['discount'] . '%)</b></td><td>- ₹' . indian_number_format($discount_amt) . '</td></tr>';
}

if ($quotation['gst_included'] === 'yes') {
    $html .= '<tr><td><b>GST (' . $quotation['gst_rate'] . '%)</b></td><td>₹' . indian_number_format($gst_amt) . '</td></tr>';
}

if (!empty($quotation['transport_type'])) {
    $html .= '<tr><td><b>Transport (' . ucwords(strtolower($quotation['transport_type'])) . ')</b></td><td>₹' . indian_number_format($transport_amt) . '</td></tr>';
}

$html .= '<tr style="background-color:#f8f8f8;">
            <td><b>Grand Total</b></td><td><b>₹' . indian_number_format($grand_total) . '</b></td>
          </tr>
        </table>';

    $this->writeHTML($html, true, false, false, false, '');
}

    // Pricing Details
//    public function pricingDetails($quotation) {
//        $this->addSectionTitle('Pricing Details');
//        $this->SetFont('dejavusans', '', 10);
//
//        $html = '<table border="1" cellpadding="5" cellspacing="0">
//    <tr><td><b>Adult Price</b></td><td>₹' . indian_number_format($quotation['adult_price'] * $quotation['adults']) . '</td></tr>
//    <tr><td><b>Child Price</b></td><td>₹' . indian_number_format($quotation['child_price'] * $quotation['child']) . '</td></tr>
//    <tr><td><b>Extra Bed Price</b></td><td>₹' . indian_number_format($quotation['extra_bed_price'] * $quotation['extrabed']) . '</td></tr>
//    <tr><td><b>Discount</b></td><td>' . indian_number_format($quotation['discount']) . '%</td></tr>';
//
//if ($quotation['gst_included'] === 'yes') {
//    $html .= '<tr><td><b>GST Rate</b></td><td>' . indian_number_format($quotation['gst_rate']) . '%</td></tr>';
//}
//
//if (!empty($quotation['transport_type'])) {
//    $html .= '<tr><td><b>' . ucwords(strtolower($quotation['transport_type'])) . '</b></td><td>₹' . indian_number_format($quotation['transport_charges']) . '</td></tr>';
//}
//
//$html .= '<tr style="background-color:#f8f8f8;">
//            <td><b>Grand Total</b></td><td><b>₹' . indian_number_format($quotation['grand_total']) . '</b></td>
//          </tr>
//                  </table>';
//
//        $this->writeHTML($html, true, false, false, false, '');
//    }

    // Inclusions and Exclusions
   public function inclusionsExclusions($quotation) {
    $addSection = function($title, $html) {
    if ($this->GetY() > 250) $this->AddPage();
    $this->addSectionTitle($title);
    $this->SetFont('dejavusans', '', 10);
    $this->writeHTML($html, true, false, true, false, '');
};

    // Retrieve inclusions, exclusions, and remarks or set defaults
	$remarks = $quotation['remarks'] ?? 'No Description specified.';  // Add remarks
    $inclusions = $quotation['inclusions'] ?? 'No inclusions specified.';
    $exclusions = $quotation['exclusions'] ?? 'No exclusions specified.';
    

    // Add Inclusions, Exclusions, and Remarks sections to the PDF
    if (!empty($quotation['remarks'])) {
	$addSection('Description', $remarks);  // Add Remarks section
    }
    $addSection('Inclusions', $inclusions);
    $addSection('Exclusions', $exclusions);
    
}


    // Terms and Conditions
    public function termsAndConditions() {
        $this->addSectionTitle('Terms & Conditions');
        $this->SetFont('helvetica', '', 9);

        $terms = [
            "Quotation valid for 7 days from issue date.",
            "50% advance payment at booking time.",
            "Full payment required before departure.",
            "Subject to availability at the time of confirmation.",
            "Cancellation charges as per company policy."
        ];

        foreach ($terms as $term) {
            $this->MultiCell(0, 5, "- " . $term, 0, 'L', false, 1);
        }

        $this->Ln(10);
        $this->SetY(-45);
        $this->Cell(140, 5, '', 0, 0);
        $this->SetFont('dejavusans', '', 10);
        $this->Cell(50, 5, 'Authorized Signature', 'T', 0, 'C');
    }
}

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

// Create and Output
$pdf = new TravelQuotationPDF();
$pdf->SetMargins(10, 50, 10);
$pdf->SetAutoPageBreak(true, 25);
$pdf->AddPage();
$pdf->customerAndQuotationDetails($quotation);
$pdf->packageDetails($quotation);
$pdf->hotelDetails($quotationId);
$pdf->pricingDetails($quotation);
$pdf->inclusionsExclusions($quotation);
$pdf->termsAndConditions();
ob_clean(); // clear any accidental output buffer content (optional safety)
$pdf->Output('quotation_' . $quotation['quotation_no'] . '.pdf', 'I');
?>
