<?php
include("../db/cn.php");
include("common/tx.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Fetch order details from the database
$orderId = isset($_GET['inv_id']) ? mysqli_real_escape_string($connection, $_GET['inv_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = null;

if ($orderId) {
    $query = "SELECT * FROM purchase WHERE inv_id = '$orderId'";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $orderDetails = mysqli_fetch_all($result, MYSQLI_ASSOC);
        $order = $orderDetails[0];
        $outletName = $order['outlet_name'];
        $loginUser = $order['login_user'];
        $userRole = $order['user_role'];
        $outletAddress = $order['outlet_address'];
        $dateTime = $order['date_time'];
        $totalAmount = $order['net_amount'];
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = $order['discount_amount'];
        $discounted = $order['discounted'];
        $discountPer = $order['discount_per'];
        $cashAmount = $order['cash_amount'];
        $changeAmount = $order['change_amount'];
        $taxAmount = $order['tax_amount'];
        $pre = $order['pre_amount'];
        $close = $order['grand_amount'];
        $cutting = $order['cutting'];
        $loading = $order['loading'];
        $vehicle_rent = $order['vehicle_rent'];
        $ctn = $order['ctn'];
        $bora = $order['bora'];
    }
}

$content = ob_get_clean();

function sendToPrinter($result) {
    $printerName = "EPSON_TM_T88V_Receipt";
    $handle = @fopen("USB", "w");
    if (!$handle) {
        echo "Error opening printer on Windows. Check the printer port and connection.";
        return;
    }
    fwrite($handle, $result);
    fclose($handle);
    echo "";
}

sendToPrinter($content);

// ---------- Exit logic (kept exactly as original) ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && is_numeric($changeAmount)) {
        $checkQuery = "SELECT 1 FROM supplier_closing WHERE supplier_name = '$customerName' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            $updateQuery = "UPDATE supplier_closing SET closing_balance = $changeAmount WHERE supplier_name = '$customerName'";
            $updateResult = mysqli_query($connection, $updateQuery);
            if ($updateResult) {
                echo "<script type='text/javascript'>window.location.href = 'purchase_n.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Update failed: " . mysqli_error($connection) . "</p>";
            }
        } else {
            $insertQuery = "INSERT INTO supplier_closing (
               supplier_name, opening_cash, cash_purchase, credit_purchase,
                cash_paid, closing_balance, user_name, user_role,
                outlet_name, outlet_address, date_time
            ) VALUES (
                '$customerName', 0, 0, 0, 0, $changeAmount, '$userName', '$useRole', '$outlet_name', '$outlet_address', NOW()
            )";
            $insertResult = mysqli_query($connection, $insertQuery);
            if ($insertResult) {
                echo "<script type='text/javascript'>window.location.href = 'purchase_n.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Invoice | <?php echo htmlspecialchars($tx); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #1e293b;
            --border: #e2e8f0;
            --bg-light: #f8fafc;
            --text: #0f172a;
            --text-muted: #64748b;
            --accent: #0f766e;
            --danger: #b91c1c;
            --success: #15803d;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #f1f5f9;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 40px 20px;
            color: var(--text);
        }

        .invoice {
            width: 210mm;
            max-width: 210mm;
            background: #ffffff;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            border-radius: 12px;
            overflow: hidden;
            position: relative;
        }

        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            .invoice {
                width: 100%;
                max-width: 100%;
                box-shadow: none;
                border-radius: 0;
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none !important;
            }
            @page {
                size: A4;
                margin: 15mm;
            }
            .invoice-body {
                padding: 15mm 15mm 10mm;
            }
        }

        .invoice-header {
            background: var(--primary);
            color: white;
            padding: 24px 36px;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
        }
        .company-info h1 {
            font-size: 28px;
            font-weight: 700;
            letter-spacing: -0.5px;
            margin-bottom: 4px;
        }
        .company-info .address {
            font-size: 13px;
            opacity: 0.85;
            line-height: 1.5;
        }
        .invoice-badge {
            text-align: right;
        }
        .invoice-badge .label {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 2px;
            opacity: 0.8;
        }
        .invoice-badge .number {
            font-size: 24px;
            font-weight: 700;
            margin-top: 4px;
        }

        .invoice-body {
            padding: 36px 36px 24px;
        }

        .meta-row {
            display: flex;
            flex-wrap: wrap;
            gap: 30px;
            margin-bottom: 28px;
        }
        .meta-box {
            flex: 1;
            min-width: 180px;
        }
        .meta-box h3 {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-muted);
            margin-bottom: 10px;
            border-bottom: 1px solid var(--border);
            padding-bottom: 6px;
        }
        .meta-box p {
            font-size: 14px;
            line-height: 1.6;
            font-weight: 500;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 28px 0 20px;
        }
        .items-table thead th {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--text-muted);
            border-bottom: 2px solid var(--border);
            padding: 12px 8px;
            text-align: left;
        }
        .items-table thead th:nth-child(n+3) {
            text-align: right;
        }
        .items-table tbody td {
            padding: 14px 8px;
            border-bottom: 1px solid var(--border);
            font-size: 14px;
            vertical-align: top;
        }
        .items-table tbody td:nth-child(n+3) {
            text-align: right;
        }
        .item-name {
            font-weight: 600;
            color: var(--text);
        }

        .totals-section {
            margin-top: 28px;
            display: flex;
            justify-content: flex-end;
        }
        .totals-grid {
            width: 340px;
            display: flex;
            flex-direction: column;
            gap: 8px;
            font-size: 15px;
        }
        .totals-grid .row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
        }
        .totals-grid .row.total {
            font-weight: 700;
            font-size: 17px;
            border-top: 2px solid var(--primary);
            padding-top: 12px;
            margin-top: 4px;
        }
        .totals-grid .row.discount {
            color: var(--danger);
        }
        .totals-grid .row.payment {
            color: var(--success);
        }

        .policy-note {
            margin-top: 30px;
            background: var(--bg-light);
            border-radius: 8px;
            padding: 16px 20px;
            font-size: 13px;
            color: var(--text-muted);
            border: 1px solid var(--border);
            line-height: 1.6;
        }
        .policy-note strong {
            color: var(--text);
            display: block;
            margin-bottom: 8px;
        }

        .footer {
            margin-top: 24px;
            text-align: center;
            font-size: 12px;
            color: var(--text-muted);
            border-top: 1px solid var(--border);
            padding-top: 20px;
        }

        .button-group {
            background: white;
            padding: 20px 36px;
            border-top: 1px solid var(--border);
            display: flex;
            gap: 14px;
            justify-content: flex-end;
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            font-family: 'Inter', sans-serif;
            display: inline-block;
        }
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        .btn-primary:hover {
            background: #0f172a;
        }
        .btn-secondary {
            background: #e2e8f0;
            color: #334155;
        }
        .btn-secondary:hover {
            background: #cbd5e1;
        }

        @media screen and (max-width: 800px) {
            .invoice-header {
                flex-direction: column;
                gap: 16px;
            }
            .meta-row {
                flex-direction: column;
                gap: 20px;
            }
            .items-table thead {
                display: none;
            }
            .items-table tbody td {
                display: block;
                text-align: right;
                padding: 8px;
            }
            .items-table tbody td::before {
                content: attr(data-label);
                float: left;
                font-weight: 600;
                text-transform: uppercase;
                color: var(--text-muted);
            }
            .totals-grid {
                width: 100%;
            }
        }
    </style>
</head>
<body>
<div class="invoice">
    <div class="invoice-header">
        <div class="company-info">
            <h1><?php echo htmlspecialchars($tx); ?></h1>
            <div class="address">
                Shop No 82<br>
                📞 03212121294. 03362121292
            </div>
        </div>
        <div class="invoice-badge">
            <div class="label">Purchase Invoice</div>
            <div class="number">#<?php echo $orderId; ?></div>
        </div>
    </div>

    <div class="invoice-body">
        <!-- Meta Information -->
        <div class="meta-row">
            <div class="meta-box">
                <h3>Date & Time</h3>
                <p><?php echo date('d M, Y  h:i A', strtotime($dateTime)); ?></p>
            </div>
            <div class="meta-box">
                <h3>Supplier</h3>
                <p>
                    <?php if(!empty($customerName) && $customerName != 'walkin'): ?>
                        <?php echo htmlspecialchars($customerName); ?><br>
                        <small><?php echo htmlspecialchars($customerPhone); ?></small>
                    <?php else: ?>
                        N/A
                    <?php endif; ?>
                </p>
            </div>
            <div class="meta-box">
                <h3>Payment Method</h3>
                <p><?php echo ucfirst($paidBy); ?></p>
            </div>
        </div>

        <!-- Items Table -->
        <table class="items-table">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Unit</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Total</th>
                    <th>Disc %</th>
                    <th>PKR</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orderDetails as $order): ?>
                <tr>
                    <td data-label="Product" class="item-name"><?php echo htmlspecialchars($order['product_name'] ?? ''); ?></td>
                    <td data-label="Unit" class="item-name"><?php echo htmlspecialchars($order['product_unit'] ?? ''); ?></td>
                    <td data-label="Qty"><?php echo $order['product_quantity']; ?></td>
                    <td data-label="Price"><?php echo number_format(floatval($order['product_price']), 2); ?></td>
                    <td data-label="Total"><?php echo number_format(floatval($order['product_total']), 2); ?></td>
                    <td data-label="Disc %"><?php echo $order['discount']; ?>%</td>
                    <td data-label="PKR"><?php echo number_format(floatval($order['net_amount']), 2); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Totals -->
        <div class="totals-section">
            <div class="totals-grid">
                <div class="row">
                    <span>Total Amount</span>
                    <span>Rs. <?php echo number_format(floatval($discountedAmount ?? 0), 2); ?></span>
                </div>
                <div class="row">
                    <span>Cutting</span>
                    <span>Rs. <?php echo number_format(floatval($cutting ?? 0), 2); ?></span>
                </div>
                <div class="row">
                    <span>Loading</span>
                    <span>Rs. <?php echo number_format(floatval($loading ?? 0), 2); ?></span>
                </div>
                <div class="row">
                    <span>Vehicle Rent</span>
                    <span>Rs. <?php echo number_format(floatval($vehicle_rent ?? 0), 2); ?></span>
                </div>
                <div class="row">
                    <span>CTN</span>
                    <span>Rs. <?php echo number_format(floatval($ctn ?? 0), 2); ?></span>
                </div>
                <div class="row">
                    <span>Bora</span>
                    <span>Rs. <?php echo number_format(floatval($bora ?? 0), 2); ?></span>
                </div>
                <div class="row">
                    <span>Previous Amount</span>
                    <span>Rs. <?php echo number_format(floatval(@$pre), 2); ?></span>
                </div>
                <div class="row total">
                    <span>Grand Total</span>
                    <span>Rs. <?php echo number_format(floatval($close ?? 0), 2); ?></span>
                </div>
                <?php if($cashAmount > 0): ?>
                <div class="row payment">
                    <span>Amount Received</span>
                    <span>Rs. <?php echo number_format(floatval($cashAmount), 2); ?></span>
                </div>
                <div class="row payment">
                    <span>Cash Remaining</span>
                    <span>Rs. <?php echo number_format(floatval($changeAmount), 2); ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Exchange Policy -->
        <div class="policy-note">
            <strong>📋 Notes</strong>
            1. Exchanges are accepted within 7 days from the date of purchase.<br>
            2. Items must be in their original condition with all tags attached.<br>
            3. A valid receipt or proof of purchase is required for all exchanges.
        </div>

        <!-- Footer -->
        <div class="footer">
            Thanks for visiting!<br>
            This is a computer‑generated invoice.
        </div>
    </div>

    <!-- Buttons (hidden when printing) -->
    <div class="button-group no-print">
        <button class="btn btn-primary" onclick="window.print();">🖨️ Print Invoice</button>
        <form method="post" style="display:inline;">
            <button type="submit" name="exit" class="btn btn-secondary">✖️ Exit</button>
        </form>
    </div>
</div>

<script>
    // Print optimizations
    window.addEventListener('beforeprint', () => {
        document.querySelectorAll('.no-print').forEach(el => el.style.display = 'none');
    });
    window.addEventListener('afterprint', () => {
        document.querySelectorAll('.no-print').forEach(el => el.style.display = '');
    });

    // Ctrl+P shortcut
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            window.print();
        }
    });
</script>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>