@extends('admin.layouts.app')

@section('title', 'View MPR')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Manual Purchase Requisition</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{ route('purchase-requisitions.index') }}">Manual Purchase
                        Requisitions</a></li>
                <li class="breadcrumb-item active">View Manual Purchase Requisition</li>
            </ul>
        </div>
        <div class="d-flex align-items-center gap-2">
            @if(auth()->user()->hasPermission('Purchase Requisition Create'))
                <a href="{{ route('purchase-requisitions.create') }}" class="btn btn-added">
                    <img src="{{ asset('assets/img/icons/plus.svg') }}" alt="img" class="me-1">Create New
                </a>
            @endif
            @if ($previous)
                <a href="{{ route('purchase-requisitions.show', $previous->id) }}" class="btn btn-outline-secondary">
                    &laquo; Previous
                </a>
            @else
                <button class="btn btn-outline-secondary" disabled>&laquo; Previous</button>
            @endif

            <div class="dropdown">
                <button class="btn btn-primary dropdown-toggle" type="button" id="jumpToPODropdown"
                    data-bs-toggle="dropdown" aria-expanded="false">
                    Jump to MPR
                </button>
                <ul class="dropdown-menu" aria-labelledby="jumpToPODropdown"
                    style="max-height: 300px; overflow-y: auto; min-width: 300px;">
                    <li class="px-3 py-2">
                        <input type="text" class="form-control form-control-sm" id="poSearchInput"
                            placeholder="Search code..." onkeyup="filterPOs()" oninput="filterPOs()">
                    </li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    @foreach ($allPRs as $po)
                        <li>
                            <a class="dropdown-item po-item {{ $po->id == $purchaseRequisition->id ? 'active fw-bold' : '' }}"
                                href="{{ route('purchase-requisitions.show', $po->id) }}"
                                data-po-code="{{ strtolower($po->code) }}"
                                data-po-date="{{ $po->created_at->format('d/m/Y') }}">
                                <span>{{ $po->code }}</span>
                            </a>
                        </li>
                    @endforeach
                </ul>
            </div>

            @if ($next)
                <a href="{{ route('purchase-requisitions.show', $next->id) }}" class="btn btn-outline-secondary">
                    Next &raquo;
                </a>
            @else
                <button class="btn btn-outline-secondary" disabled>Next &raquo;</button>
            @endif

            <a href="{{ route('purchase-requisitions.edit', $purchaseRequisition->id) }}" class="btn btn-light">
                <img src="{{ asset('assets/img/icons/edit.svg') }}" alt="Edit">
            </a>

            <button class="btn btn-primary" onclick="aaprintWithTimestamp()">
                <img src="{{ asset('assets/img/icons/printer.svg') }}" alt="Print">
            </button>
        </div>
        {{-- <div class="text-right">
            <button class="btn btn-primary" onclick="aaprintWithTimestamp()">Print Manual Purchase Requisition</button> --}}
        {{-- <button class="btn btn-primary" onclick="printWithTimestamp()">Print Manual Purchase Requisition</button> --}}
        {{-- </div> --}}
    </div>

    <!-- Card Component -->
    <div class="card" id="main_card">
        <div class="card-body">
            @if ($purchaseRequisition->is_approved == 1)
                <span
                    class="position-absolute top-0 end-0 ps-2 mt-2 pe-3 bg-success text-light approved-target">{{ $purchaseRequisition->is_approved == 1 ? 'Approved' : '' }}</span>
            @endif
            <div class="row justify-content-between">
                <div class="col-auto">
                    <div class="d-flex">
                        <div class="flex-shrink-0">
                            <img src="{{ asset($purchaseRequisition->company->logo_path ? 'images/company/' . $purchaseRequisition->company->logo_path : 'images/company/logo.png') }}"
                                class="mb-2" style="height: 80px">
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h5 class="fw-bold">{{ $purchaseRequisition->company->name }}</h5>
                            <p class="fs-6 mb-0">{{ $purchaseRequisition->company->address }}</p>
                            <p class="fs-6 mb-0">{{ $purchaseRequisition->company->phone }}</p>
                        </div>
                    </div>
                </div>
                <div class="col-auto text-end print-header">
                    <h2>Manual Purchase Requisition</h2>
                </div>
            </div>

            <table class="table mt-2">
                <tr>
                    <th>PR No.</th>
                    <td>{{ $purchaseRequisition->code }}</td>
                    <th>Date</th>
                    <td>{{ $purchaseRequisition->created_at->format('Y-m-d') }}</td>
                    <th>Required Date</th>
                    <td>{{ \Carbon\Carbon::parse($purchaseRequisition->required_date)->format('Y-m-d') }}</td>
                </tr>
                <tr>
                    <th>Supplier</th>
                    <td colspan="3">{{ $purchaseRequisition->supplier->name ?? 'N/A' }}</td>
                </tr>
            </table>

            <table class="table table-hover mt-2">
                <thead class="">
                    <tr>
                        <th>#</th>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>Unit</th>
                        <th>Price</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($purchaseRequisition->purchaseRequisitionItems as $key => $purchaseRequisitionItem)
                        <tr>
                            <td>{{ $key + 1 }}</td>
                            <td>{{ $purchaseRequisitionItem->name }}</td>
                            <td>{{ $purchaseRequisitionItem->quantity }}</td>
                            <td>{{ $purchaseRequisitionItem->unit }}</td>
                            <td>{{ $purchaseRequisitionItem->price }}</td>
                            <td>{{ $purchaseRequisitionItem->amount }}</td>
                        </tr>
                    @endforeach
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="5" class="text-right footer-row"> <strong>Total</strong></th>
                        <th class=" footer-row">{{ number_format($purchaseRequisition->total_amount, 2) }}</th>
                    </tr>
                    {{-- <tr>
                        <td colspan="6"><br></td>
                    </tr> --}}
                </tfoot>
            </table>
            @if ($purchaseRequisition->special_instructions)
                <div style="" id="notes_div">
                    <strong>Note:</strong> {!! nl2br($purchaseRequisition->special_instructions) !!}
                </div>
            @endif

            <footer class="footer">
                <div class="signature-section" style="margin-top: auto;">
                    <div style="display: flex; justify-content: space-around; align-items: end;">
                        <div style="width: 200px; text-align: center;">
                            <span
                                style="font-size: 14px; font-weight: bold;">{{ $purchaseRequisition->createdBy->name ?? null }}</span>
                            <hr style="width: 100%; margin: 3px 0px;">
                            <span style="font-size: 14px;">Prepared by</span>
                        </div>
                        <div style="width: 200px; text-align: center;">
                            <hr style="width: 100%; margin: 3px 0px;">
                            <span style="font-size: 14px;">Checked by</span>
                        </div>
                        <div style="width: 200px; text-align: center;">
                            <hr style="width: 100%; margin: 3px 0px;">
                            <span style="font-size: 14px;">Approved by</span>
                        </div>
                    </div>
                    <div class="text-end" id="printTimestampContainer"></div>
                </div>
            </footer>
        </div>
    </div>

    <!-- Print-only signature block (shown only during printing, forced to its own last page) -->
    <div class="print-only-signature card" id="printSignatureCopy" aria-hidden="true">
        <div class="card-body">
            <div style="display:flex; justify-content: space-around; align-items: end;">
                <div style="width: 200px; text-align: center;">
                    <span
                        style="font-size: 14px; font-weight: bold;">{{ $purchaseRequisition->createdBy->name ?? null }}</span>
                    <hr style="width: 100%; margin: 3px 0px;">
                    <span style="font-size: 14px;">Prepared by</span>
                </div>
                <div style="width: 200px; text-align: center;">
                    <hr style="width: 100%; margin: 3px 0px;">
                    <span style="font-size: 14px;">Checked by</span>
                </div>
                <div style="width: 200px; text-align: center;">
                    <hr style="width: 100%; margin: 3px 0px;">
                    <span style="font-size: 14px;">Approved by</span>
                </div>
            </div>
            <div class="text-end" id="printTimestampContainerPrintOnly"></div>
        </div>
    </div>

    <script>
        function aaprintWithTimestamp(containerId = 'printTimestampContainer') {
            const targets = [containerId, 'printTimestampContainerPrintOnly'];

            // --- inject timestamp
            targets.forEach(id => {
                let container = document.getElementById(id);
                if (!container) {
                    container = document.createElement('div');
                    container.id = id;
                    const fallback = document.querySelector('.footer') || document.body;
                    fallback.appendChild(container);
                }

                container.innerHTML = '';
                const timestampDiv = document.createElement('div');
                timestampDiv.className = 'generated-print-timestamp';
                timestampDiv.style.cssText =
                    'text-align: right; margin-top: 6px; font-size: 12px; color: #666;';
                const now = new Date();
                const formatted = now.toLocaleString('en-GB', {
                    hour12: false
                });
                timestampDiv.innerHTML = '<strong>Printed on:</strong> ' + formatted;
                container.appendChild(timestampDiv);
            });

            // --- Create style for timestamp only (no page rules)
            if (!document.getElementById('printSignatureCopy')) {
                const printStyle = document.createElement('style');
                printStyle.id = 'printSignatureCopy';
                printStyle.textContent = `
            @media print {
                .generated-print-timestamp {
                    visibility: visible !important;
                    color: #666 !important;
                    font-size: 12px !important;
                }
                #printSignatureCopy {
                    visibility: visible !important;
                }
            }
        `;
                document.head.appendChild(printStyle);
            }

            // --- Handle signature placement: only on last page
            const sig = document.getElementById('printSignatureCopy');
            let sigClone = null;
            if (sig) {
                // Hide all existing ones
                sig.style.display = 'none';

                // Clone and append to body (prints last)
                sigClone = sig.cloneNode(true);
                sigClone.style.display = 'block';
                sigClone.style.position = 'relative';
                sigClone.style.pageBreakBefore = 'always';
                document.body.appendChild(sigClone);
            }

            // --- Print
            setTimeout(() => {
                window.print();

                // Cleanup
                setTimeout(() => {
                    document.querySelectorAll('.generated-print-timestamp').forEach(n => n.remove());
                    const styleElement = document.getElementById('printTimestampStyle');
                    if (styleElement) styleElement.remove();

                    // remove clone and restore original signature
                    if (sigClone) sigClone.remove();
                    if (sig) sig.style.display = 'block';
                }, 500);
            }, 150);
        }
    </script>
@endsection

<style>
    /* keep existing non-print styles (no change) */
    .print-header {
        margin-top: 5px !important;
    }

    .footer-row {
        padding-bottom: 0 !important;
    }

    #notes_div {
        margin-top: 10px;
        font-size: 14px;
    }

    #printSignatureCopy {
        display: none !important;
    }

    /* Print layout — targeted and predictable */
    @media print {
        .footer-row {
            padding-bottom: 4rem !important;
        }

        #notes_div {
            padding-bottom: 4.5rem !important;
        }

        #printSignatureCopy {
            display: block !important;
            position: fixed !important;
            bottom: 0 !important;
            left: 0;
            width: 100%;
            margin-top: 20px !important;
        }

        /* hide UI controls that should not appear on print */
        .page-header,
        .no-print,
        button,
        .btn {
            display: none !important;
        }

        /* page settings */
        @page {
            size: auto;
            margin: 3% !important;
        }

        html,
        body {
            background: none !important;
            height: auto !important;
            margin: 0;
            padding: 0;
            /* margin-bottom: 5rem !important;
            padding-bottom: 5rem !important; */
        }

        /* make the main card take normal flow in print */
        /* #main_card, */
        .card,
        .card-body {
            position: static !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            box-shadow: none !important;
            border: none !important;
        }

        #main_card {
            margin-top: -3rem !important;
            margin-bottom: 4rem !important;
            /* padding-bottom: 3rem !important; */
        }

        /* Keep table colors */
        .table-primary th {
            background-color: #cfe2ff !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            color: #000 !important;
        }

        .approved-target {
            background-color: #198754 !important;
            color: white !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        /* -------- SIGNATURE / LAST PAGE HANDLING --------
           Strategy:
           - Hide the on-screen signature section during print (it may appear in middle of content).
           - Show the separate .print-only-signature block only during printing.
           - Force .print-only-signature to start on a new page and use a full-page flex
             container so the signature rows sit at the bottom of that page.
        -------------------------------------------------- */

        /* hide the inline signature in the printed card body */
        .footer {
            display: none !important;
        }

        /* show the print-only signature copy */
        /* .print-only-signature {
            display: block !important;
        } */

        /* force print-only signature to its own page */
        /* .print-only-signature {
            page-break-before: always !important;
            break-before: page !important;
            height: calc(100vh - 2cm);
            display: flex !important;
            flex-direction: column;
            justify-content: flex-end;
            align-items: stretch;
            padding: 0.5cm 1cm;
            box-sizing: border-box;
        }

        .print-only-signature .signature-section {
            display: block !important;
            page-break-inside: avoid !important;
            break-inside: avoid !important;
        } */

        /* timestamp container in print-only copy */
        #printTimestampContainerPrintOnly {
            display: block !important;
            text-align: right !important;
            margin-top: 10px !important;
            font-size: 12px !important;
            color: #666 !important;
        }

        /* small helper: prevent table rows from splitting awkwardly */
        table {
            page-break-inside: auto !important;
        }

        tr {
            page-break-inside: avoid !important;
            page-break-after: auto !important;
        }
    }
</style>
