<?php
// Include the main TCPDF library.
require_once('vendor/tcpdf/tcpdf.php');

// Function to sanitize input data
function sanitize_input($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // --- DATA COLLECTION AND SANITIZATION ---
    $customerName = isset($_POST['customerName']) ? sanitize_input($_POST['customerName']) : 'N/A';
    $phoneNumber = isset($_POST['phoneNumber']) ? sanitize_input($_POST['phoneNumber']) : 'N/A';
    $email = isset($_POST['email']) ? sanitize_input($_POST['email']) : 'N/A';
    $passengers = isset($_POST['passengers']) ? sanitize_input($_POST['passengers']) : 'N/A';
    $departureAirport = isset($_POST['departureAirport']) ? sanitize_input($_POST['departureAirport']) : 'N/A';
    $arrivalAirport = isset($_POST['arrivalAirport']) ? sanitize_input($_POST['arrivalAirport']) : 'N/A';
    $departureDate = isset($_POST['departureDate']) ? sanitize_input($_POST['departureDate']) : 'N/A';
    $returnDate = isset($_POST['returnDate']) && !empty($_POST['returnDate']) ? sanitize_input($_POST['returnDate']) : 'One Way';
    $airline = isset($_POST['airline']) ? sanitize_input($_POST['airline']) : 'N/A';
    $cabinClass = isset($_POST['cabinClass']) ? sanitize_input($_POST['cabinClass']) : 'N/A';
    
    $layover = "No";
    $layoverAirport = 'N/A';
    $layoverDuration = 'N/A';
    if (isset($_POST['layoverToggle'])) {
        $layover = "Yes";
        $layoverAirport = isset($_POST['layoverAirport']) ? sanitize_input($_POST['layoverAirport']) : 'N/A';
        $layoverDuration = isset($_POST['layoverDuration']) ? sanitize_input($_POST['layoverDuration']) : 'N/A';
    }

    $fare = isset($_POST['fare']) ? (float)$_POST['fare'] : 0;
    $totalFare = isset($_POST['totalFare']) ? sanitize_input($_POST['totalFare']) : '0.00';
    
    $infants = isset($_POST['infants']) ? (int)$_POST['infants'] : 0;
    $infantFare = isset($_POST['infantFare']) ? (float)$_POST['infantFare'] : 0;
    $totalInfantFare = isset($_POST['totalInfantFare']) ? sanitize_input($_POST['totalInfantFare']) : '0.00';
    $infantBaggage = isset($_POST['infantBaggage']) ? sanitize_input($_POST['infantBaggage']) : 'N/A';

    $checkedBaggage = isset($_POST['checkedBaggage']) ? sanitize_input($_POST['checkedBaggage']) : 'N/A';
    $weightPerPiece = isset($_POST['weightPerPiece']) ? sanitize_input($_POST['weightPerPiece']) : 'N/A';
    $handBaggage = isset($_POST['handBaggage']) ? sanitize_input($_POST['handBaggage']) : 'N/A';
    $baggageNotes = isset($_POST['baggageNotes']) ? sanitize_input($_POST['baggageNotes']) : 'N/A';

    $extraChargeDescription = isset($_POST['extraChargeDescription']) ? sanitize_input($_POST['extraChargeDescription']) : 'N/A';
    $extraChargePrice = isset($_POST['extraChargePrice']) ? (float)$_POST['extraChargePrice'] : 0;

    $grandTotal = isset($_POST['grandTotal']) ? sanitize_input($_POST['grandTotal']) : '0.00';
    $otherRequests = isset($_POST['otherRequests']) ? sanitize_input($_POST['otherRequests']) : 'None';

    // --- PDF GENERATION ---

    // Extend the TCPDF class to create custom Header and Footer
    class MYPDF extends TCPDF {
        //Page header
        public function Header() {
            // Set font
            $this->SetFont('helvetica', 'B', 18);
            
            // Company Details
            $this->SetY(15);
            $this->Cell(0, 10, 'Safari Muscat Tourism LLC', 0, true, 'C', 0, '', 0, false, 'M', 'M');
            $this->SetFont('helvetica', '', 10);
            $this->Cell(0, 8, 'Central Market, Salalah, Dhofar, Sultanate of Oman', 0, true, 'C', 0, '', 0, false, 'M', 'M');
            $this->Cell(0, 8, 'PO Box: 211 | Phone: +968 99737165', 0, true, 'C', 0, '', 0, false, 'M', 'M');

            // Title
            $this->SetFont('helvetica', 'B', 20);
            $this->SetY(45);
            $this->Cell(0, 15, 'Airfare Request Quotation', 0, true, 'C', 0, '', 0, false, 'M', 'M');
            
            // Add a line under the title
            $this->SetLineStyle(array('width' => 0.2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(150, 150, 150)));
            $this->Line(15, $this->GetY(), $this->getPageWidth() - 15, $this->GetY());

            // Line break
            $this->Ln(8);
        }

        // Page footer
        public function Footer() {
            // Position at 15 mm from bottom
            $this->SetY(-15);
            // Set font
            $this->SetFont('helvetica', 'I', 8);
            // Page number
            $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        }
    }

    // Create new PDF document
    $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // Set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Safari Muscat Tourism LLC');
    $pdf->SetTitle('Airfare Request - ' . $customerName);
    $pdf->SetSubject('Airfare Request Quotation');

    // Set default header data
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // Set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    // Set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT); // Increased top margin for header
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // Set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // Set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // Add a page
    $pdf->AddPage();

    // Set font
    $pdf->SetFont('helvetica', '', 10);

    // --- CONTENT ---
    $html = '';

    // Customer & Flight Details
    $html .= '
    <table border="0" cellpadding="5" cellspacing="0" width="100%">
        <tr>
            <td width="50%">
                <h3 style="color:#333;">Customer Details</h3>
                <b>Name:</b> ' . $customerName . '<br>
                <b>Phone:</b> ' . $phoneNumber . '<br>
                <b>Email:</b> ' . $email . '<br>
                <b>Passengers:</b> ' . $passengers . '
            </td>
            <td width="50%">
                <h3 style="color:#333;">Flight Details</h3>
                <b>Departure:</b> ' . $departureAirport . '<br>
                <b>Arrival:</b> ' . $arrivalAirport . '<br>
                <b>Departure Date:</b> ' . $departureDate . '<br>
                <b>Return Date:</b> ' . $returnDate . '
            </td>
        </tr>
        <tr>
            <td colspan="2"><hr></td>
        </tr>
        <tr>
            <td>
                <b>Airline:</b> ' . $airline . '<br>
                <b>Cabin Class:</b> ' . $cabinClass . '
            </td>
            <td>
                <b>Layover:</b> ' . $layover . '<br>
                <b>Layover Airport:</b> ' . $layoverAirport . '<br>
                <b>Layover Duration:</b> ' . $layoverDuration . '
            </td>
        </tr>
    </table>
    <br><br>
    ';

    // Fare & Baggage Details
    $html .= '
    <h3 style="color:#333;">Fare & Baggage Summary</h3>
    <table border="1" cellpadding="5" cellspacing="0" width="100%">
        <tr style="background-color:#f5f5f5;">
            <th width="70%">Description</th>
            <th width="30%" align="right">Amount (OMR)</th>
        </tr>
        <tr>
            <td>Passenger Fare (' . $passengers . ' x ' . number_format($fare, 3) . ')</td>
            <td align="right">' . $totalFare . '</td>
        </tr>';
    
    if ($infants > 0) {
        $html .= '
        <tr>
            <td>Infant Fare (' . $infants . ' x ' . number_format($infantFare, 3) . ')</td>
            <td align="right">' . $totalInfantFare . '</td>
        </tr>';
    }

    if ($extraChargePrice > 0) {
        $html .= '
        <tr>
            <td>' . $extraChargeDescription . '</td>
            <td align="right">' . number_format($extraChargePrice, 3) . '</td>
        </tr>';
    }

    $html .= '
        <tr style="background-color:#e0e0e0;">
            <td align="right"><b>GRAND TOTAL</b></td>
            <td align="right"><b>' . $grandTotal . '</b></td>
        </tr>
    </table>
    <br><br>
    ';

    // Baggage Details
    $html .= '
    <h3 style="color:#333;">Baggage Allowance</h3>
    <table border="0" cellpadding="5" cellspacing="0" width="100%">
        <tr>
            <td width="50%">
                <b>Adult Checked Baggage:</b> ' . $checkedBaggage . ' pc(s) @ ' . $weightPerPiece . ' kg each<br>
                <b>Adult Hand Baggage:</b> ' . $handBaggage . ' kg
            </td>
            <td width="50%">
                <b>Infant Baggage:</b> ' . $infantBaggage . '
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <b>Baggage Notes:</b> ' . $baggageNotes . '
            </td>
        </tr>
    </table>
    <br><br>
    ';

    // Additional Comments
    $html .= '
    <h3 style="color:#333;">Additional Comments</h3>
    <p>' . nl2br($otherRequests) . '</p>
    ';

    // Print text using writeHTMLCell()
    $pdf->writeHTML($html, true, false, true, false, '');

    // Close and output PDF document
    $pdf->Output('Safari_Muscat_Airfare_Request_' . preg_replace("/[^a-zA-Z0-9]/", "_", $customerName) . '.pdf', 'D');

} else {
    // If the form was not submitted, redirect to the form page
    header("Location: index.php");
    exit();
}
?>
