<?php

namespace App\Http\Controllers;

use Filament\Notifications\Notification;
use Illuminate\Http\Request;
use Mpdf\Mpdf;
use Mpdf\QrCode\Output;
use Mpdf\QrCode\QrCode;

class PalletController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    public function downloadReprintQrPdf($palletNo)
    {
        $qrCode = new QrCode($palletNo);
        $output = new Output\Png;
        $qrBinary = $output->output($qrCode, 100);
        $qrBase64 = base64_encode($qrBinary);

        return '
        <html>
        <head>
             <style>
            body { margin: 0; padding: 0; width: 60mm; height: auto; font-size: 10pt; font-family: DejaVu Sans, sans-serif; }
            .sticker-table { width: 60mm; height: 14mm; border-collapse: collapse; page-break-after: always; }
            .qr-cell { width: 14mm; text-align: right; vertical-align: bottom; padding-left: 0mm; padding-top: 0mm; }
            .text-cell { text-align: left; vertical-align: middle; font-size: 20pt; padding-left: 1mm; padding-top: 2mm; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; }
            img.qr { width: 19mm; height: 19mm; display: block; }
        </style>
        </head>
        <body>
            <table class="sticker-table">
                <tr>
                    <td class="qr-cell">
                        <img class="qr" src="data:image/png;base64,'.$qrBase64.'" alt="QR" />
                    </td>
                    <td class="text-cell">
                        '.htmlspecialchars($palletNo).'
                    </td>
                </tr>
            </table>
            <script>
                window.onload = function () {
                    window.print();
                    setTimeout(function () {
                        window.close();
                    }, 500); // Wait 0.5 seconds before closing
                };
                </script>
        </body>
        </html>
        ';

        // $mpdf = new Mpdf([
        //     'mode' => 'utf-8',
        //     'format' => [60, 14],
        //     'margin_left' => 0,
        //     'margin_right' => 0,
        //     'margin_top' => 0,
        //     'margin_bottom' => 0,
        //    // 'tempDir' => '/var/www/storage/mpdf-tmp',
        // ]);

        // $mpdf->WriteHTML($html);
        // // Output PDF to browser for printing
        // $mpdf->Output('qr-label.pdf', 'I');
    }

    public function downloadReprintProcess($plant, $item, $process_order, $coil_number, $name)
    {
        // dd($plant,$item,$process_order,$coil_number);

        $processOrder = \App\Models\ProcessOrder::where('plant_id', $plant)
            ->where('item_id', $item)
            ->where('process_order', $process_order)
            ->where('coil_number', $coil_number)
            ->first();

        if (! $processOrder) {
            return response()->json(['error' => 'Process order not found'], 404);
        }

        $receivedQuantity = $processOrder->received_quantity;
        $machineName = $processOrder->machine_name;
        $user = $processOrder->created_by;

        $icode = \App\Models\Item::find($item);

        $pCode = \App\Models\Plant::find($plant);

        $plCode = $pCode->code;

        if (! $plCode) {
            Notification::make()
                ->title('Unknown Plant')
                ->body('Plant not found.')
                ->warning()
                ->send();
        }

        if (! $icode) {
            Notification::make()
                ->title('Unknown Item')
                ->body('Item not found.')
                ->warning()
                ->send();
        }

        $itCode = $icode->code;

        $itemAgaPlant = \App\Models\Item::where('code', $itCode)
            ->where('plant_id', $plant)
            ->first();

        if (! $itemAgaPlant) {
            Notification::make()
                ->title('Unknown Item')
                ->body("Item not found against plant code $plCode.")
                ->warning()
                ->send();
        } else {
            $itemDescription = $itemAgaPlant->description;
        }

        $nowDT = now()->format('d-m-Y H:i:s');

        // Build QR content
        $qrContent = "{$receivedQuantity}|{$itCode}|{$process_order}-{$coil_number}";

        $qrCode = new QrCode($qrContent);
        $output = new Output\Png;
        $qrBinary = $output->output($qrCode, 100);
        $qrBase64 = base64_encode($qrBinary);

        return '
        <html>
        <head>
            <style>
                @page {
                    size: 60mm 30mm;
                    margin: 0;
                }

                body {
                    margin: 0;
                    padding: 0;
                    width: 60mm;
                    font-size: 9pt;
                    font-family: "DejaVu Sans Condensed", "FreeSans", sans-serif;
                }

                .sticker-table {
                    width: 60mm;
                    border-collapse: collapse;
                    page-break-inside: avoid;
                }

                .text-cell {
                    text-align: left;
                    vertical-align: top;
                    font-size: 9pt;
                    padding-left: 2mm;
                    padding-top: 2mm;   /* was 6mm ❌ */
                    font-weight: bold;
                    line-height: 1.1;   /* IMPORTANT */
                    white-space: nowrap;
                    width: 40mm;
                }

                .qr-cell {
                    width: 20mm;
                    text-align: center;
                    vertical-align: middle;
                }

                .lbl {
                    display: inline-block;
                    width: 11mm;
                    font-weight: bold;
                }

                .text-cell b {
                    font-size: 10pt;    /* was 12pt ❌ */
                    font-weight: bold;
                }

                img.qr {
                    width: 12mm;
                    height: 12mm;
                    display: block;
                    margin: auto;
                }
            </style>
        </head>
        <body>
            <table class="sticker-table">
                <tr>
                    <td class="text-cell">
                        <span class="lbl">D/T</span>: '.htmlspecialchars($nowDT).'<br>
                        <span class="lbl">OP ID</span>: '.htmlspecialchars($user).'<br>
                        <span class="lbl">PO NO</span>: '.htmlspecialchars($process_order).'<br>
                        <span class="lbl">M/C</span>: '.htmlspecialchars($itCode).'<br>
                        <span class="lbl">DES</span>: '.htmlspecialchars($itemDescription).'<br>
                        <span class="lbl">WGT</span>: <b>'.htmlspecialchars($receivedQuantity).' KGS</b><br>
                        <span class="lbl">MAC</span>: '.htmlspecialchars($machineName).'
                    </td>
                    <td class="qr-cell">
                        <img class="qr" src="data:image/png;base64,'.$qrBase64.'" alt="QR" />
                    </td>
                </tr>
            </table>

            <script>
                window.onload = function () {
                    window.print();
                    setTimeout(function () { window.close(); }, 500);
                };
            </script>
        </body>
        </html>
        ';

    }

    public function downloadQrPdf($palletNo)
    {
        $qrCode = new QrCode($palletNo);
        $output = new Output\Png;
        $qrBinary = $output->output($qrCode, 100);
        $qrBase64 = base64_encode($qrBinary);

        $htmlBlock = '
        <table class="sticker-table">
            <tr>
                <td class="qr-cell">
                    <img class="qr" src="data:image/png;base64,'.$qrBase64.'" alt="QR" />
                </td>
                <td class="text-cell">
                    '.htmlspecialchars($palletNo).'
                </td>
            </tr>
        </table>';

        return '
    <html>
    <head>
        <style>
            body { margin: 0; padding: 0; width: 60mm; height: auto; font-size: 10pt; font-family: DejaVu Sans, sans-serif; }
            .sticker-table { width: 60mm; height: 14mm; border-collapse: collapse; page-break-after: always; }
            .qr-cell { width: 14mm; text-align: right; vertical-align: bottom; padding-left: -8mm; padding-top: 0mm; }
            .text-cell { text-align: left; vertical-align: middle; font-size: 22pt; padding-left: 1mm; padding-top: 2mm; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; }
            img.qr { width: 19mm; height: 19mm; display: block; }
        </style>
    </head>
    <body>
        '.$htmlBlock.$htmlBlock.'
        <script>
            window.onload = function () {
                window.print();
                setTimeout(function () {
                    window.close();
                }, 1000); // Wait 1 second before closing
            };
        </script>
    </body>
    </html>';

        // $mpdf = new Mpdf([
        //     'mode' => 'utf-8',
        //     'format' => [60, 14],
        //     'margin_left' => 0,
        //     'margin_right' => 0,
        //     'margin_top' => 0,
        //     'margin_bottom' => 0,
        //    // 'tempDir' => '/var/www/storage/mpdf-tmp',
        // ]);

        // $mpdf->WriteHTML($html);
        // // Output PDF to browser for printing
        // $mpdf->Output('qr-label.pdf', 'I');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
