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

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

class MYPDF extends TCPDF {
    public function Header() {
        $this->Image(__DIR__.'/../assets/img/logo.png', 10, 8, 50);
        $this->SetFont('dejavusans', '', 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('dejavusans', 'B', 14);
        $this->SetTextColor(10, 69, 110);
        $this->Cell(0, 10, 'Payment Receipt', 0, 1, 'C');
        $this->SetTextColor(0, 0, 0);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
    }

    public function Footer() {
        $this->SetY(-20);
        $this->SetDrawColor(12, 69, 110);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->Ln(2);
        $this->SetFont('dejavusans', '', 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);
    }
}

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;
}

$payment_id = (int) $_GET['payment_id'];

$sql = "SELECT pb.*, pp.*, c.name AS customer_name, c.email AS customer_email, c.phone AS customer_phone, c.address AS customer_address,
        CONCAT('R-', pp.receipt_no) AS receipt_number,
        DATE_FORMAT(pp.payment_date, '%d-%m-%Y') AS payment_date_formatted
        FROM package_payments pp
        LEFT JOIN package_bookings pb ON pb.id = pp.booking_id
        LEFT JOIN customers c ON c.id = pb.customer_id
        WHERE pp.id = $payment_id";

$result = $conn->query($sql);
$data = $result->fetch_assoc();

if (!$data) {
    die("Payment not found.");
}

$gst_amount = 0;
$base_amount = $data['grand_total'];
$show_gst = false;

if ($data['gst_included'] == 'yes') {
    $show_gst = true;
    $gst_rate = $data['gst_rate'];
    $gst_amount = ($base_amount * $gst_rate) / (100 + $gst_rate);
    $base_amount -= $gst_amount;
}

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetMargins(15, 40, 15);
$pdf->AddPage();
$pdf->SetFont('dejavusans', '', 10);

$html = '
<style>
    td { font-size: 10pt; padding: 5px; }
    th { background-color: #0A446E; color: white; font-size: 10pt; padding: 8px; }
    table { border-collapse: collapse; width: 100%; }
    .section-title { background-color: #0A446E; color: white; font-weight: bold; padding: 5px; }
    .bold { font-weight: bold; }
    .text-right { text-align: right; }
    .text-center { text-align: center; }
    .footer { font-size: 8pt; color: #888; text-align: center; }
</style>

<br><br><br>
<table cellpadding="2" cellspacing="0" border="1" style="border-color:#0A446E;" width="100%">
    <tr>
        <!-- LEFT: Customer Info (70% Width) -->
        <td width="70%" valign="top">
            <table cellpadding="2" cellspacing="0" width="100%">
                <tr>
                    <td width="20%" class="bold">Name:</td>
                    <td width="80%">' . htmlspecialchars($data['customer_name']) . '</td>
                </tr>
                <tr>
                    <td class="bold">Address:</td>
                    <td>' . nl2br(htmlspecialchars($data['customer_address'])) . '</td>

                </tr>
                <tr>
                    <td class="bold">Mobile:</td>
                    <td>' . htmlspecialchars($data['customer_phone']) . '</td>
                </tr>
                <tr>
                    <td class="bold">Email:</td>
                    <td>' . htmlspecialchars($data['customer_email']) . '</td>
                </tr>
            </table>
        </td>

        <!-- RIGHT: Receipt Info (30% Width) -->
        <td width="30%" valign="top">
            <table cellpadding="2" cellspacing="0" width="100%">
                <tr>
                    <td width="50%" class="bold">Receipt No:</td>
                    <td width="50%">' . htmlspecialchars($data['receipt_number']) . '</td>
                </tr>
                <tr>
                    <td class="bold">Date:</td>
                    <td>' . htmlspecialchars($data['payment_date_formatted']) . '</td>
                </tr>
            </table>
        </td>
    </tr>
</table><br><br>

<table border="1" cellpadding="6" cellspacing="0" style="border-color: #0A446E;">
    <tr>
        <td width="50%"><strong>Invoice No:</strong> ' . $data['booking_no'] . '</td>
        <td><strong>Package:</strong> ' . $data['package_name'] . ' (' . $data['destination'] . ')</td>
    </tr>
    <tr>
        <td><strong>Travel Date:</strong> ' . $data['travel_date'] . '</td>
        <td><strong>Duration:</strong> ' . $data['nights'] . ' Nights / ' . $data['rooms'] . ' Room(s)</td>
    </tr>
</table><br>

<table border="1" cellpadding="6" cellspacing="0" style="border-color: #0A446E;">
    <tr>
        <th colspan="2" class="section-title">Payment Details</th>
    </tr>
    <tr>
        <td><strong>Amount Paid:</strong></td>
        <td>₹ ' . indian_number_format($data['amount']) . '</td>
    </tr>
    <tr>
        <td><strong>Payment Mode:</strong></td>
        <td>' . strtoupper($data['payment_mode']) . '</td>
    </tr>';

if ($data['payment_mode'] == 'cheque') {
    $html .= '<tr><td><strong>Cheque No:</strong></td><td>' . $data['cheque_no'] . '</td></tr>';
} elseif ($data['payment_mode'] == 'upi') {
    $html .= '<tr><td><strong>UPI Ref:</strong></td><td>' . $data['upi_details'] . '</td></tr>';
} elseif ($data['payment_mode'] == 'bank_transfer') {
    $html .= '<tr><td><strong>Bank Name:</strong></td><td>' . $data['bank_name'] . '</td></tr>';
    $html .= '<tr><td><strong>Cheque No:</strong></td><td>' . $data['cheque_no'] . '</td></tr>';
}

$html .= '</table><br>

<table border="1" cellpadding="6" cellspacing="0" style="border-color: #0A446E;">
    <tr>
        <th colspan="2" class="section-title">Package Pricing Summary</th>
    </tr>
    <tr>
        <td><strong>Total:</strong></td>
        <td>₹ ' . indian_number_format($data['total_amount']) . '</td>
    </tr>';

if ($data['discount'] > 0) {
    $html .= '<tr>
                <td><strong>Discount (' . $data['discount'] . '%):</strong></td>
                <td>₹ ' . indian_number_format($data['discount_amount']) . '</td>
              </tr>';
}

if ($show_gst) {
    $html .= '<tr>
                <td><strong>GST (' . $data['gst_rate'] . '%):</strong></td>
                <td>₹ ' . indian_number_format($gst_amount) . '</td>
              </tr>';
}

$html .= '  
    <tr>
        <td><strong>Grand Total:</strong></td>
        <td><strong>₹ ' . indian_number_format($data['grand_total']) . '</strong></td>
    </tr>
</table><br>

<p><strong>Remarks:</strong> ' . ($data['remarks'] ?: 'N/A') . '</p><br><br>

<table width="100%">
    <tr>
        <td class="bold">Customer Signature</td>
        <td class="text-right bold">Authorized Signature</td>
    </tr>
</table><br><br>

<p class="text-center footer">Thank you for booking with us!</p>';

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('receipt_' . $data['receipt_number'] . '.pdf', 'I');
?>
