<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');


require __DIR__ . '/library/fpdf/fpdf.php';
// require __DIR__ . '/data_source.php';
$zdb = $_SESSION["zdbyear_" . $dbname];
$zroot = $_SESSION["zdir"];
mysqli_select_db($conn, $zdb);
$id = $_REQUEST["vouchno"];

function get_booking_data($conn, $id)
{
    // -------------------------------------------------------------------
    // REAL DATABASE VERSION (uncomment and adapt when ready)
    // -------------------------------------------------------------------


    $gtdt = mysqli_query($conn, "SELECT * FROM bookform WHERE vouchno = '$id'") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($gtdt);

    if (!$row) {
        return null; // voucher.php will show a "booking not found" message
    }


    return [
        'date' => date('d-m-Y', strtotime($row['vouchdt'])),
        'name' => $row['haji'] . " " . $row['surname'],
        'co' => $row['agent_company'],
        'pax' => $row['fullno'] . ' PAX',
        'paxno' => $row['fullno'],
        'adultrate' => $row['full2'],
        'adultamt' => $row['fullamt'],
        'discrate' => $row['disc2'],
        'discno' => $row['discno'],
        'discamt' => $row['discamt'],
        'package' => $row['batchno'],
        'dep_date' => date('d-m-Y', strtotime($row['depdate'])),
        'makkah_room' => $row['makkah_room_type'],
        'contact' => $row['tel'] . " -\n" . $row['fname'],
        'azizia_room' => $row['azizia_room_type'],
        'moallim' => $row['moallim'],
        'company' => $row['agent_company'],
        'cheque1' => $row['paydtl1'],
        'cheque2' => $row['paydtl2'],
        'rem1' => $row['rem1'],
        'rem2' => $row['rem2'],
        'rem3' => $row['rem3'],
        'subtotal' => (float) $row['nettot'],
        'tcs_pax' => $row['tcs_pax'],
        'tcs_rate' => (float) $row['tcs_rate'],
        'tcs_total' => (float) $row['tcs_total'],
        'grand_total' => (float) $row['netamt'],
    ];


    // -------------------------------------------------------------------
    // SAMPLE DATA (used until the DB block above is wired up)
    // -------------------------------------------------------------------
    // $sample = [
    //     'date'        => '08-01-2026',
    //     'name'        => 'QURESHI IMRAN MOHAMED SULEMAN',
    //     'co'          => 'REHBAR TOURS',
    //     'pax'         => '02 PAX',
    //     'package'     => 'SILVER CLASS',
    //     'dep_date'    => '12TH MAY',
    //     'makkah_room' => '4 BED SHR',
    //     'contact'     => "9892535675 -\nMUSHTAQ BHAI\nREHBAR",
    //     'azizia_room' => '5/6 BED SHR',
    //     'moallim'     => 'A MOALLIM',
    //     'company'     => 'REHBAR TOURS',
    //     'cheque1'     => '5,25,000 x 2 = 10,50,000/-',
    //     'cheque2'     => '4,80,000/-',
    //     'note'        => '',
    //     'line_items'  => [
    //         ['label' => 'ADULT',       'pax' => 2, 'rate' => 765000,  'total' => 1530000, 'red' => false],
    //         ['label' => 'DISCOUNT',    'pax' => 2, 'rate' => -40000,  'total' => -80000,  'red' => true],
    //         ['label' => 'Aziza 4 Bed', 'pax' => 2, 'rate' => 15000,   'total' => 30000,   'red' => false],
    //     ],
    //     'subtotal'    => 1480000,
    //     'tcs_pax'     => 5,
    //     'tcs_rate'    => 500000,
    //     'tcs_total'   => 50000,
    //     'grand_total' => 1530000,
    // ];

    // return $sample;
}



/** Format a number the Indian way, e.g. 1530000 -> "15,30,000" */
function inr($num)
{
    $num = (int) round((float) $num);
    $neg = $num < 0;
    $num = abs($num);
    $str = (string) $num;
    if (strlen($str) <= 3) {
        $formatted = $str;
    } else {
        $last3 = substr($str, -3);
        $rest = strrev(substr($str, 0, -3));
        $rest = implode(',', str_split($rest, 2));
        $rest = strrev($rest);
        $formatted = $rest . ',' . $last3;
    }
    return ($neg ? '-' : '') . $formatted;
}

class HajjVoucherPDF extends FPDF
{
    /** Draw an ellipse outline/fill, centered at ($x,$y) with radii $rx/$ry */
    function Ellipse($x, $y, $rx, $ry, $style = 'D')
    {
        if ($style == 'F') {
            $op = 'f';
        } elseif ($style == 'FD' || $style == 'DF') {
            $op = 'B';
        } else {
            $op = 'S';
        }
        $lx = 4 / 3 * (M_SQRT2 - 1) * $rx;
        $ly = 4 / 3 * (M_SQRT2 - 1) * $ry;
        $k = $this->k;
        $h = $this->h;
        $this->_out(sprintf(
            '%.2F %.2F m %.2F %.2F %.2F %.2F %.2F %.2F c',
            ($x + $rx) * $k,
            ($h - $y) * $k,
            ($x + $rx) * $k,
            ($h - ($y - $ly)) * $k,
            ($x + $lx) * $k,
            ($h - ($y - $ry)) * $k,
            $x * $k,
            ($h - ($y - $ry)) * $k
        ));
        $this->_out(sprintf(
            '%.2F %.2F %.2F %.2F %.2F %.2F c',
            ($x - $lx) * $k,
            ($h - ($y - $ry)) * $k,
            ($x - $rx) * $k,
            ($h - ($y - $ly)) * $k,
            ($x - $rx) * $k,
            ($h - $y) * $k
        ));
        $this->_out(sprintf(
            '%.2F %.2F %.2F %.2F %.2F %.2F c',
            ($x - $rx) * $k,
            ($h - ($y + $ly)) * $k,
            ($x - $lx) * $k,
            ($h - ($y + $ry)) * $k,
            $x * $k,
            ($h - ($y + $ry)) * $k
        ));
        $this->_out(sprintf(
            '%.2F %.2F %.2F %.2F %.2F %.2F c %s',
            ($x + $lx) * $k,
            ($h - ($y + $ry)) * $k,
            ($x + $rx) * $k,
            ($h - ($y + $ly)) * $k,
            ($x + $rx) * $k,
            ($h - $y) * $k,
            $op
        ));
    }

    /**
     * Draw one row of bordered "Excel style" grid cells.
     * $cells is an array of: [text, width, align, bold, fontSize, rgbColor|null]
     */
    function gridRow($x, $y, $h, $cells)
    {
        $this->SetXY($x, $y);
        foreach ($cells as $c) {
            $text = $c[0];
            $w = $c[1];
            $align = $c[2] ?? 'L';
            $bold = $c[3] ?? false;
            $size = $c[4] ?? 9;
            $color = $c[5] ?? null;

            $this->SetFont('helvetica', $bold ? 'B' : '', $size);
            if ($color) {
                $this->SetTextColor($color[0], $color[1], $color[2]);
            } else {
                $this->SetTextColor(0, 0, 0);
            }
            $this->Cell($w, $h, $text, 1, 0, $align);
        }
        $this->SetTextColor(0, 0, 0);
    }
}

/**
 * Renders the full voucher onto $pdf using the booking data array $d.
 * See data_source.php for the expected keys.
 */
function render_voucher(HajjVoucherPDF $pdf, array $d)
{
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $pdf->SetDrawColor(90, 90, 90);
    $pdf->SetLineWidth(0.15);

    $left = 8;                    // left margin (mm)
    $labelW1 = 32;
    $valueW1 = 80;
    $labelW2 = 22;
    $valueW2 = 60;
    $fullW = $labelW1 + $valueW1 + $labelW2 + $valueW2; // 194mm
    $y = 10;

    // --- Title banner + logo box -------------------------------------
    $titleW = $labelW1 + $valueW1 + $labelW2; // 124mm
    $logoW = $valueW2;                       // 70mm
    $rowH = 20;
    $pdf->gridRow($left, $y, $rowH, [
        ['', $titleW, 'C'],
        ['', $logoW, 'C'],
    ]);
    $pdf->Ellipse($left + $titleW / 2, $y + $rowH / 2, $titleW / 2 - 8, $rowH / 2 - 3.5, 'D');
    $pdf->SetXY($left, $y);
    $pdf->SetFont('helvetica', 'B', 18);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell($titleW, $rowH, 'HAJJ BOOKING FORM', 0, 0, 'C');
    $y += $rowH;

    // --- Date row -------------------------------------------------------
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['Date :', $titleW, 'R', true, 10],
        [$d['date'], $logoW, 'C', true, 12],
    ]);
    $y += $rowH;

    // --- Name row ---------------------------------------------------------
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['Name:', $labelW1, 'L', true, 9],
        [$d['name'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);
    $y += $rowH;

    // --- C/o + No. of Pax row ---------------------------------------------
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['C/o. :', $labelW1, 'L', true, 9],
        [$d['co'], $valueW1, 'L', true, 10],
        ['No. of Pax :', $labelW2, 'L', true, 8],
        [$d['pax'], $valueW2, 'C', true, 10],
    ]);
    $y += $rowH;

    // --- Package + Departure date row --------------------------------------
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['Pckg. Name :', $labelW1, 'L', true, 9],
        [$d['package'], $valueW1, 'L', true, 10],
        ['Dep. Date :', $labelW2, 'L', true, 8],
        [$d['dep_date'], $valueW2, 'C', true, 10],
    ]);
    $y += $rowH;

    // --- Makkah room type + Contact row (multi-line contact) ---------------
    $rowH = 16;
    $pdf->gridRow($left, $y, $rowH, [
        ['Mak/Med Room Type :', $labelW1, 'L', true, 7.5],
        [$d['makkah_room'], $valueW1, 'L', true, 10],
        ['Contact :', $labelW2, 'L', true, 8],
    ]);
    $contactX = $left + $labelW1 + $valueW1 + $labelW2;
    $pdf->SetXY($contactX, $y);
    $pdf->SetFont('helvetica', 'B', 9.5);
    $pdf->MultiCell($valueW2, $rowH / 2, $d['contact'], 1, 'L');
    $y += $rowH;

    // --- Azizia room type + Moallim row -------------------------------------
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['Azizia Room Type :', $labelW1, 'L', true, 7.5],
        [$d['azizia_room'], $valueW1, 'L', true, 10],
        ['MOALLIM :', $labelW2, 'L', true, 8],
        [$d['moallim'] . " MOALLIM", $valueW2, 'C', true, 10],
    ]);
    $y += $rowH;

    // --- Passenger fare table -----------------------------------------------
    $descW = 90;
    $paxW = 22;
    $rateW = 40;
    $totalW = 42; // descW+paxW+rateW+totalW = 194

    $rowH = 8;
    $pdf->gridRow($left, $y, $rowH, [
        ['PASSENGER DETAILS', $descW, 'C', true, 9],
        ['PAX', $paxW, 'C', true, 9],
        ['Rate (INR)', $rateW, 'C', true, 9],
        ['Total (INR)', $totalW, 'C', true, 9],
    ]);
    $y += $rowH;

    // foreach ($d['line_items'] as $item) {
    $rowH = 9;
    $color = !empty($item['red']) ? [200, 0, 0] : null;
    $pdf->gridRow($left, $y, $rowH, [
        ["ADULT", $descW, 'L', !empty($item['red']), 10, $color],
        [(string) $d['paxno'], $paxW, 'C', !empty($item['red']), 10, $color],
        [inr($d['adultrate']), $rateW, 'R', false, 10, $color],
        [inr($d['adultamt']), $totalW, 'R', true, 10, $color],
    ]);
    $y += $rowH;

    $rowH = 9;
    $color = !empty($item['red']) ? [200, 0, 0] : null;
    $pdf->gridRow($left, $y, $rowH, [
        ["DISCOUNT", $descW, 'L', !empty($item['red']), 10, $color],
        [(string) $d['discno'], $paxW, 'C', !empty($item['red']), 10, $color],
        [inr($d['discrate']), $rateW, 'R', false, 10, $color],
        [inr($d['discamt']), $totalW, 'R', true, 10, $color],
    ]);
    $y += $rowH;
    // }

    // Subtotal
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['Total', $descW + $paxW + $rateW, 'L', true, 10],
        [inr($d['subtotal']), $totalW, 'R', true, 10],
    ]);
    $y += $rowH;

    // TCS
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['5% T.C.S Refundable', $descW, 'L', true, 9],
        [(string) $d['tcs_pax'], $paxW, 'C', true, 10],
        [inr($d['tcs_rate']), $rateW, 'R', true, 10],
        [inr($d['tcs_total']), $totalW, 'R', true, 10],
    ]);
    $y += $rowH;

    // Grand total
    $rowH = 10;
    $pdf->gridRow($left, $y, $rowH, [
        ['GRAND TOTAL', $descW + $paxW + $rateW, 'L', true, 11],
        [inr($d['grand_total']), $totalW, 'R', true, 11],
    ]);
    $y += $rowH;

    // --- Company / cheque details --------------------------------------------
    $rowH = 9;
    $pdf->gridRow($left, $y, $rowH, [
        ['COMPANY :', $labelW1, 'L', true, 9],
        [$d['company'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);
    $y += $rowH;

    $pdf->gridRow($left, $y, $rowH, [
        ['CHQ 1 :', $labelW1, 'L', true, 9],
        [$d['cheque1'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);
    $y += $rowH;

    $pdf->gridRow($left, $y, $rowH, [
        ['CHQ 2 :', $labelW1, 'L', true, 9],
        [$d['cheque2'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);
    $y += $rowH;

    // Blank spacer row
    $pdf->gridRow($left, $y, $rowH, [['', $fullW, 'L']]);
    $y += $rowH;

    // Note row + two blank lines for handwritten notes
    $pdf->gridRow($left, $y, $rowH, [
        ['Note :', $labelW1, 'L', true, 9],
        [$d['rem1'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);
    $y += $rowH;

    $pdf->gridRow($left, $y, $rowH, [
        ['', $labelW1, 'L', true, 9],
        [$d['rem2'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);
    $y += $rowH;

    $pdf->gridRow($left, $y, $rowH, [
        ['', $labelW1, 'L', true, 9],
        [$d['rem3'], $valueW1 + $labelW2 + $valueW2, 'L', true, 10],
    ]);

    $y += $rowH;
    // for ($i = 0; $i < 2; $i++) {
    //     $pdf->gridRow($left, $y, $rowH, [['', $fullW, 'L']]);
    //     $y += $rowH;
    // }

    // --- Footer fine print -----------------------------------------------------
    $y += 2;
    $pdf->SetFont('helvetica', '', 7.5);
    $pdf->SetXY($left, $y);
    $pdf->MultiCell($fullW, 4, ". 5% GST Included\n. 5% or 20% TCS applicable\n. Documents will be delivered\n  only after full payment is received.", 0, 'L');
    $y = $pdf->GetY() + 2;

    // --- Signature line ----------------------------------------------------
    $halfW = $fullW / 2;
    $pdf->SetDrawColor(0, 0, 0);
    $pdf->Line($left, $y, $left + $halfW - 4, $y);
    $pdf->Line($left + $halfW + 4, $y, $left + $fullW, $y);
    $pdf->SetFont('helvetica', 'B', 8);
    $pdf->SetXY($left, $y + 1);
    $pdf->Cell($halfW, 5, 'SALES CO-ORDINATOR', 0, 0, 'C');
    $pdf->SetXY($left + $halfW, $y + 1);
    $pdf->Cell($halfW, 5, 'PASSENGER SIGNATURE', 0, 0, 'C');
}

// ============================================================================
// Entry point
// ============================================================================
if (PHP_SAPI === 'cli') {
    // CLI usage: php voucher.php [id] [output_path]
    $id = $argv[1] ?? 'sample';
    $outPath = $argv[2] ?? (__DIR__ . '/hajj_voucher.pdf');

    $data = get_booking_data($conn, $id);
    if ($data === null) {
        fwrite(STDERR, "Booking not found for id: $id\n");
        exit(1);
    }
    $pdf = new HajjVoucherPDF('P', 'mm', 'A4');
    render_voucher($pdf, $data);
    $pdf->Output('F', $outPath);
    echo "Saved: $outPath\n";
} else {
    // Web usage: voucher.php?id=123[&download=1]
    $id = $_GET['vouchno'] ?? 'sample';
    $data = get_booking_data($conn, $id);
    if ($data === null) {
        http_response_code(404);
        echo 'Booking not found.';
        exit;
    }
    $pdf = new HajjVoucherPDF('P', 'mm', 'A4');
    render_voucher($pdf, $data);
    $dest = !empty($_GET['download']) ? 'D' : 'I';
    $pdf->Output($dest, 'hajj_voucher_' . $id . '.pdf');
}
