<?php
require_once __DIR__ . '/vendor/autoload.php';

use Mpdf\Mpdf;
use Mpdf\HTMLParserMode;

@set_time_limit(0);
@ini_set('memory_limit', '1024M');

ini_set('display_errors', 0);
error_reporting(0);

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . $host;
$url = $baseUrl . '/';

try {
    require(realpath(__DIR__ . '/../../services/Model.php'));
    $obj = new Model();

    /* ===========================
       1) URL decode (GET data)
    =========================== */
    $data = $_GET['data'] ?? '';
    if (!$data) die('No data found');

    $decoded = base64_decode(urldecode($data), true);
    if ($decoded === false) {
        $decoded = base64_decode(urldecode($data)); // fallback
    }

    $tokens = json_decode($decoded, true);

    if (!is_array($tokens) || empty($tokens)) {
        die('Invalid token data');
    }

    // sanitize
    $tokens = array_values(array_filter(array_map('intval', $tokens)));
    if (empty($tokens)) {
        die('No valid token');
    }

    /* ===========================
       2) mPDF init (ONE PDF)
    =========================== */
    $mpdf = new Mpdf([
        'orientation'  => 'P',
        'format'       => 'A4',
        'default_font' => 'nikosh',
        'tempDir'      => __DIR__ . '/tmp'
    ]);

    $mpdf->SetAutoPageBreak(true, 8);
    $mpdf->SetDisplayMode('fullpage');

    /* ===========================
       3) Global CSS (same design)
    =========================== */
    $mpdf->WriteHTML('
        <style>
            .divider { border-top: 1.5px dotted red; margin: 6px 0;width:100% }
            body { font-family: nikosh; }
            .no-break { page-break-inside: avoid; }
        </style>
    ', HTMLParserMode::HEADER_CSS);

    /* ===========================
       4) Settings load once
    =========================== */
    $logo        = $obj->getSettingValue('logo', 'logo');
    $CompanyName = $obj->getSettingValue('excel', 'name');
    $address     = $obj->getSettingValue('address', 'address');
    $mobile      = $obj->getSettingValue('mobile', 'mobile');
    $email       = $obj->getSettingValue('email', 'email');

    $writtenAny = false;
    $firstPage = true;

    /* ===========================
       5) Loop tokens
    =========================== */
    foreach ($tokens as $token) {

        $agentDetail = $obj->view_all_by_cond('tbl_agent', "ag_id=$token");
        if (!$agentDetail) {
            continue;
        }

        $account = $obj->details_by_cond('tbl_account', "agent_id='$token'");
        if ($account && !empty($account['entry_date'])) {
            $datetime = new DateTime($account['entry_date']);
            $month = $datetime->format('F');
            $year  = $datetime->format('Y');
        } else {
            $month = date('F');
            $year  = date('Y');
        }

        $uniqueReceiptNumber = date('YmdHis') . '-' . mt_rand(10, 99);

        if (!$firstPage) $mpdf->AddPage();
        $firstPage = false;

        foreach ($agentDetail as $agentDetails) {

            $agg_id = (int)($agentDetails['ag_id'] ?? 0);
            if ($agg_id <= 0) continue;

            // due
            $rowDue = $obj->rawSqlSingle("SELECT dueadvance FROM customer_billing WHERE agid='$agg_id'");
            $totalDue = intval($rowDue["dueadvance"] ?? 0);

            $extraRow = '';
            if ($totalDue > 0) {
                $extraRow = '<tr><td>2</td><td>Previous Due</td><td>--</td><td>--</td><td>' .
                    number_format($totalDue > intval($agentDetails["taka"]) ? $totalDue - intval($agentDetails["taka"]) : 0, 2) .
                    '</td></tr>';
            } elseif ($totalDue < 0) {
                $extraRow = '<tr><td>2</td><td>Advanced Payment</td><td>--</td><td>--</td><td>' .
                    number_format(abs($totalDue), 2) .
                    '</td></tr>';
            }

            $types = ['Customer Copy', 'Office Copy'];
            $copyCount = 0;

            $cusId   = $agentDetails["cus_id"] ?? '';
            $agName   = $agentDetails["ag_name"] ?? '';
            $agMobile = $agentDetails["ag_mobile_no"] ?? '';
            $agAddr   = $agentDetails["ag_office_address"] ?? '';
            $agIp     = $agentDetails["ip"] ?? ($agentDetails["ip"] ?? 'N/A');
            $agMb     = $agentDetails["mb"] ?? '';
            $agTaka   = intval($agentDetails["taka"] ?? 0);

            foreach ($types as $copy) {
                $copyCount++;

                $bsd = '';
                if ($copyCount === 2) {
                    $bsd = '<hr style="border: none;border-top: 1px dotted #000; margin: 20px 0;">
                            <small style="font-size:6pt;">Powered by Bangladesh Software Development (BSD)</small>';
                }

                $billAmount = ($totalDue < $agTaka) ? ($totalDue < 0 ? 0 : $totalDue) : $agTaka;

                $html = '
                <div class="no-break" style="margin-bottom: 10px;">
                    <div style="text-align:right; font-weight:bold; color:#2E7D32; font-size: 10pt;">' . $copy . '</div>
                    <div style="font-family: Arial; font-size: 7pt; line-height: 1.2;">
                        <div style="display: flex; align-items: center; gap: 5px;">
                            <img src="' . $url . $logo . '" width="50" />
                            <div>
                                <div style="font-size: 12pt; font-weight: bold; color:#4CAF50;">' . $CompanyName . '<span style="color:#2E7D32;"></span></div>
                                <div style="font-size: 9pt; color: #666;">' . (isset($address) && $address != '' ? $address : '') . '</div>
                                <div style="font-size: 9pt; color: red;">' . (isset($mobile) && $mobile != '' ? 'Hotline:' . $mobile : '') . '</div>
                                <div style="font-size: 9pt;">' . (isset($email) && $email != '' ? $email : '') . '</div>
                            </div>
                        </div>
                        <hr style="margin: 4px 0;">

                        <table width="100%" style="font-size:8.5pt; margin-top:3px;">
                            <tr>
                                <td>
                                    <b>To:</b><br />
                                    Name: <span style="color:red">' . $cusId . '</span><br />
                                    Name: ' . $agName . '<br />
                                    Mobile: <span style="color:red">' . $agMobile . '</span><br />
                                    Address: ' . $agAddr . '<br />
                                    IP: ' . $agIp . '<br />
                                    T.Due: ' . ($totalDue < 0 ? 0 : $totalDue) . ' BDT<br />
                                    Invoice No: ' . $uniqueReceiptNumber . '<br />
                                    Date: ' . date("Y-m-d") . '
                                </td>
                            </tr>
                        </table>

                        <table width="100%" border="1" cellspacing="0" cellpadding="3" style="border-collapse:collapse; font-size:8.5pt; margin-top:5px;">
                            <tr style="background-color:#f0f0f0;">
                                <th>SL</th>
                                <th>Description</th>
                                <th>Month</th>
                                <th>Speed</th>
                                <th>Bill Amount</th>
                            </tr>
                            <tr>
                                <td>1</td>
                                <td>Bandwidth Charge - Monthly</td>
                                <td>' . $month . '</td>
                                <td>' . $agMb . '</td>
                                <td>' . number_format($billAmount, 2) . '</td>
                            </tr>
                            ' . $extraRow . '
                        </table>

                        <table width="100%" style="font-size:8.5pt; margin-top:5px;">
                            <tr>
                                <td style="text-align:right;"><b>Total: ' . number_format(($totalDue < 0 ? 0 : $totalDue), 2) . ' BDT</b></td>
                            </tr>
                            <tr>
                                <td style="text-align:right;">In Word: ' . ucwords(convert_number_to_words(($totalDue < 0 ? 0 : $totalDue))) . ' Taka</td>
                            </tr>
                        </table>

                        <div style="font-size:6pt; margin-top:8px;">
                            <p>* Pay in cash.</p>
                            <p>* Due must be cleared before 10th of the month to avoid disconnection.</p>
                        </div>

                        <div style="text-align:right; font-size:6.5pt; margin-top:10px;">
                            Signature: ___________________
                        </div>
                        ' . $bsd . '
                    </div>
                </div>';

                $mpdf->WriteHTML($html, HTMLParserMode::HTML_BODY);
                $writtenAny = true;

                if ($copyCount === 1) {
                    $mpdf->WriteHTML('<div class="divider"></div>', HTMLParserMode::HTML_BODY);
                }
            }
        }
    }

    if (!$writtenAny) {
        $mpdf->WriteHTML('<div style="font-family:Arial;font-size:12pt;">No invoice data found for selected customers.</div>', HTMLParserMode::HTML_BODY);
    }

    $mpdf->Output("multiple_invoice.pdf", "I");
    exit;

} catch (\Throwable $e) {
    echo "PDF Error: " . $e->getMessage();
}

function convert_number_to_words($number)
{
    $hyphen = '-';
    $conjunction = ' and ';
    $separator = ', ';
    $negative = 'negative ';
    $decimal = ' point ';
    $dictionary = [
        0 => 'zero', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five',
        6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten',
        11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen',
        15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty',
        50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty',
        90 => 'ninety', 100 => 'hundred', 1000 => 'thousand',
        1000000 => 'million', 1000000000 => 'billion'
    ];

    if (!is_numeric($number)) return false;
    if ($number < 0) return $negative . convert_number_to_words(abs($number));

    $string = $fraction = null;
    if (strpos((string)$number, '.') !== false) {
        list($number, $fraction) = explode('.', (string)$number);
    }

    $number = (int)$number;

    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens = ((int) ($number / 10)) * 10;
            $units = $number % 10;
            $string = $dictionary[$tens];
            if ($units) $string .= $hyphen . $dictionary[$units];
            break;
        case $number < 1000:
            $hundreds = (int)($number / 100);
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' hundred';
            if ($remainder) $string .= $conjunction . convert_number_to_words($remainder);
            break;
        default:
            foreach ([1000000000, 1000000, 1000, 100] as $base) {
                if ($number >= $base) {
                    $numBaseUnits = (int)($number / $base);
                    $remainder = $number % $base;
                    $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$base];
                    if ($remainder) $string .= $separator . convert_number_to_words($remainder);
                    break;
                }
            }
            break;
    }

    if (isset($fraction) && is_numeric($fraction)) {
        $string .= $decimal;
        $words = [];
        foreach (str_split((string)$fraction) as $n) {
            $words[] = $dictionary[(int)$n];
        }
        $string .= implode(' ', $words);
    }

    return $string;
}
