<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

// Helper function for HTML escaping
function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// 1. Fetch Sale Data
$id = intval($_GET['id'] ?? 0);
if (!$id) { echo "Missing id"; exit; }

$stmt = $pdo->prepare("SELECT s.*, c.name AS customer_name, c.phone AS customer_phone, c.balance AS customer_balance
                        FROM sales s
                        LEFT JOIN customers c ON c.id = s.customer_id
                        WHERE s.id = ? LIMIT 1");
$stmt->execute([$id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$sale) { echo "Invoice not found"; exit; }

// 2. Fetch Sale Items
$itemsStmt = $pdo->prepare("SELECT si.*, p.sku, COALESCE(NULLIF(p.name_en,''), p.name_ar, '') AS name
                            FROM sale_items si
                            LEFT JOIN products p ON p.id = si.product_id
                            WHERE si.sale_id = ?");
$itemsStmt->execute([$id]);
$items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

// 3. Calculate Totals
$total = floatval($sale['total']);
$paid = floatval($sale['paid']);
$due = round($total - $paid, 2);

// 4. Calculate Customer Balances
$previous_balance = 0.00;
$current_balance = 0.00;
if ($sale['customer_id']) {
    $current_balance = floatval($sale['customer_balance']);
    $previous_balance = $current_balance - $due;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Invoice <?= esc($sale['invoice_no']) ?></title>

<style>
/* Base/Reset */
* { box-sizing: border-box; }
body { 
    font-family: Arial, Helvetica, sans-serif; 
    background:#fff; 
    padding:10px; 
    margin:0; 
    font-size: 13px; 
}
.invoice { 
    width: 302px; /* 80mm width */
    margin:0 auto; 
    border: 1px solid #ccc; /* Optional light border for non-print view */
    padding: 10px;
}
.header { text-align:center; margin-bottom:15px; }
.header h3 { margin:0 0 5px 0; font-size:20px; font-weight: bold; } 
.header div { margin-bottom: 2px; font-size: 12px; }

/* Separator Line */
.line { border-top:1px solid #000; margin:10px 0; }
.sub-line { border-top:1px dashed #bbb; margin:5px 0; }

/* Invoice Details (Metadata) */
.details { 
    display: flex; 
    flex-direction: column; 
    margin-bottom: 10px; 
    padding: 5px 0;
    border: 1px solid #eee; 
}
.detail-row {
    display: flex;
    justify-content: space-between;
    padding: 2px 5px;
}
.detail-row strong { width: 40%; text-align: left; }
.detail-row span { width: 60%; text-align: right; font-weight: normal; }


/* Items Table - MODIFIED FOR BOXES */
.table-box { 
    width:100%; 
    font-size:13px; 
    border-collapse:collapse; 
    text-align: left;
    border: 1px solid #000; /* Outer border for the table */
}
.table-box th, .table-box td { 
    padding:5px; /* Added padding to create space within the "box" */
    border: 1px solid #000; /* SOLID BORDERS FOR ALL CELLS */
    text-align: right;
}
.table-box th { 
    font-weight: bold;
    text-align: center;
    background-color: #f0f0f0; /* Slight background for headers */
}

/* Specific Column Styling */
.table-box th:nth-child(1), .table-box td:nth-child(1) { width: 50%; text-align: left; } /* Item */
.table-box th:nth-child(2), .table-box td:nth-child(2) { width: 10%; text-align: center; } /* Qty */
.table-box th:nth-child(3), .table-box td:nth-child(3) { width: 20%; } /* Price */
.table-box th:nth-child(4), .table-box td:nth-child(4) { width: 20%; } /* Total */

/* Item Name Details */
.small { font-size:11px; color:#555; display: block; margin-top: 2px; }

/* Summary Section */
.summary { margin-top:10px; font-size:14px; }
.summary div { 
    display: flex; 
    justify-content: space-between; 
    padding: 3px 0; 
}

/* Financial Totals */
.summary .financial-total { 
    font-size: 15px;
    font-weight: bold;
    border-top: 1px solid #000; 
    border-bottom: 2px solid #000; 
    margin-top: 5px;
}
.summary .paid-due {
    font-weight: bold;
}

/* Footer */
.footer {
    text-align: center;
    font-size: 12px;
    margin-top: 15px;
    font-style: italic;
    padding: 5px 0;
}

/* Print/Copy Buttons */
.btns { display:flex; gap:6px; margin-top:15px; }
a,button { 
    flex:1; padding:8px; background:#222; color:#fff; 
    border-radius:4px; border:none; text-align:center; 
    text-decoration:none; cursor:pointer; font-size: 14px;
}
.copy-btn { background:#0a7cff !important; }
@media print { 
    .no-print { display:none; } 
    .invoice { border: none; padding: 0; } 
}
</style>
</head>
<body>

<div class="invoice" id="invoiceData">
    <div class="header">
        <h3>TOP ACCESSORIES TOOLS</h3>
        <div>Phone: 03795761</div>
    </div>

    <div class="details">
        <div class="detail-row">
            <strong>INVOICE NO:</strong> <span><?= esc($sale['invoice_no']) ?></span>
        </div>
        <div class="detail-row">
            <strong>DATE:</strong> <span><?= date('Y-m-d H:i', strtotime($sale['created_at'])) ?></span>
        </div>
        <div class="detail-row">
            <strong>CUSTOMER:</strong> <span><?= esc($sale['customer_name'] ?: 'Cash Customer') ?></span>
        </div>
        <?php if($sale['customer_phone']): ?>
        <div class="detail-row">
            <strong>CUSTOMER PHONE:</strong> <span><?= esc($sale['customer_phone']) ?></span>
        </div>
        <?php endif; ?>
    </div>

    <table class="table-box">
        <thead>
            <tr>
                <th>DESCRIPTION</th>
                <th>QTY</th>
                <th>UNIT PRICE</th>
                <th>AMOUNT</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($items as $it): ?>
            <tr>
                <td>
                    <?= esc($it['name']) ?>
                    <?php if($it['sku']): ?><span class="small">SKU: <?= esc($it['sku']) ?></span><?php endif; ?>
                </td>
                <td><?= number_format($it['qty'],0) ?></td>
                <td><?= number_format($it['unit_price'],2) ?></td>
                <td><?= number_format($it['subtotal'],2) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="summary">
        <div class="financial-total">
            <strong>GRAND TOTAL:</strong> <span><?= number_format($total,2) ?></span>
        </div>
        
        <div class="paid-due">
            <strong>AMOUNT PAID:</strong> <span><?= number_format($paid,2) ?></span>
        </div>
        
        <div class="paid-due">
            <strong>BALANCE DUE:</strong> <span><?= number_format($due,2) ?></span>
        </div>

        <div class="line"></div>
        
        <div><strong>CUSTOMER ACCOUNT SUMMARY:</strong></div>

        <?php if($sale['customer_id']): ?>
            <div>Previous Balance: <span><?= number_format($previous_balance,2) ?></span></div>
            <div>This Invoice Due: <span><?= number_format($due,2) ?></span></div>
            <div style="font-weight: bold;">Current Account Balance: <span><?= number_format($current_balance,2) ?></span></div>
        <?php else: ?>
            <div>Cash Customer - No Account Balance Tracked</div>
        <?php endif; ?>
    </div>

    <div class="footer">
        Thank you for your valued business.
    </div>

    <div class="btns no-print">
        <button onclick="window.print()">Print Invoice</button>
        <a href="sales_create.php">New Sale</a>
        <button class="copy-btn" onclick="copyInvoice()">Copy Receipt Text</button>
    </div>

</div>

<script>
function copyInvoice() {
    let inv = document.querySelector('.invoice');
    let items = inv.querySelectorAll('tbody tr');

    let text = "";
    text += "TOP ACCESSORIES TOOLS\n";
    text += "Phone: 03795761\n";
    text += "================================\n";
    text += "INVOICE NO: <?= esc($sale['invoice_no']) ?>\n";
    text += "DATE: <?= date('Y-m-d H:i', strtotime($sale['created_at'])) ?>\n";
    text += "CUSTOMER: <?= esc($sale['customer_name'] ?: 'Cash Customer') ?>\n";
    <?php if($sale['customer_phone']): ?>
    text += "CUSTOMER PHONE: <?= esc($sale['customer_phone']) ?>\n";
    <?php endif; ?>
    text += "\nITEMS:\n";
    text += "--------------------------------\n";

    items.forEach(row => {
        let tds = row.querySelectorAll('td');
        let nameFull = tds[0].innerText.trim().replace(/\s+/g, ' '); 
        let name = nameFull.split('SKU:')[0].trim();
        let skuMatch = nameFull.match(/SKU:\s*(.*)/);
        let sku = skuMatch ? ` (SKU: ${skuMatch[1].trim()})` : '';

        let qty = tds[1].innerText.trim();
        let price = tds[2].innerText.trim();
        let total = tds[3].innerText.trim();

        text += `- ${name}${sku}\n`;
        text += `  QTY: ${qty} | PRICE: ${price} | AMOUNT: ${total}\n`;
    });

    text += "--------------------------------\n";
    text += "GRAND TOTAL: <?= number_format($total,2) ?>\n";
    text += "AMOUNT PAID: <?= number_format($paid,2) ?>\n";
    text += "BALANCE DUE: <?= number_format($due,2) ?>\n\n";

    text += "CUSTOMER ACCOUNT SUMMARY:\n";

    <?php if($sale['customer_id']): ?>
    text += "Previous Balance: <?= number_format($previous_balance,2) ?>\n";
    text += "This Invoice Due: <?= number_format($due,2) ?>\n";
    text += "Current Account Balance: <?= number_format($current_balance,2) ?>\n";
    <?php else: ?>
    text += "Cash Customer - No Account Balance Tracked\n";
    <?php endif; ?>

    text += "================================\n";
    text += "Thank you for your valued business.\n";

    navigator.clipboard.writeText(text).then(() => {
        alert("Invoice text copied successfully ✔️");
    }).catch(err => {
        console.error('Could not copy text: ', err);
        alert("Failed to copy invoice text.");
    });
}
</script>

</body>
</html>