<?php
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../session.php';

// Get sale ID from URL parameter
$sale_id = $_GET['id'] ?? 0;

if (!$sale_id) {
    die('Sale ID is required');
}

// Fetch sale data from database
$sale = row("SELECT s.*, acc.name as customer_name, acc.mobile as customer_phone 
            FROM sales s 
            LEFT JOIN accounts acc ON s.party_id = acc.id 
            WHERE s.id = ?", [$sale_id]);

if (!$sale) {
    die('Sale not found');
}

// Fetch store settings
$store = one("SELECT business_name as name, address, phone, gstin, gst_rate FROM settings WHERE id = ?", [$sale['business_id']]);

// Fetch sale items
$items = all_rows("SELECT si.item_id, ni.item_name as name, si.qty, si.rate as price 
                 FROM sale_items si 
                 LEFT JOIN new_items ni ON si.item_id = ni.id 
                 WHERE si.sale_id = ?", [$sale_id]);

$invoice = [
    'invoice_no'   => $sale['bill_no'] ?: ('INV-' . $sale['id']),
    'date'         => date('d M Y', strtotime($sale['sale_date'])),
    'customer'     => $sale['customer_name'] ?: 'Walk-in Customer',
    'phone'        => $sale['customer_phone'] ?: 'N/A',
    'payment_mode' => $sale['payment_terms'] ?: 'Cash'
];

$gst_percent = $store['gst_rate'] ?? 5;
$discount = $sale['total_discount'] ?? 0;

// Calculations
$subtotal = $sale['subtotal'] ?? 0;
$cgst = $sale['cgst'] ?? 0;
$sgst = $sale['sgst'] ?? 0;
$gst_total = $cgst + $sgst;
$grand_total = $sale['grand_total'] ?? 0;
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice <?= $invoice['invoice_no'] ?></title>

<style>
    body {
        font-family: "Segoe UI", Arial, sans-serif;
        background: #f2f4f7;
        padding: 20px;
    }

    .invoice {
        max-width: 820px;
        margin: auto;
        background: #fff;
        padding: 30px;
        border-radius: 6px;
        box-shadow: 0 0 10px rgba(0,0,0,.08);
    }

    .header {
        display: flex;
        justify-content: space-between;
        border-bottom: 2px solid #222;
        padding-bottom: 15px;
        margin-bottom: 20px;
    }

    .store h2 {
        margin: 0;
        font-size: 22px;
    }

    .store small {
        color: #555;
        line-height: 1.6;
    }

    .invoice-title {
        text-align: right;
    }

    .invoice-title h1 {
        margin: 0;
        font-size: 28px;
        letter-spacing: 2px;
    }

    .info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        font-size: 14px;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
    }

    th {
        background: #222;
        color: #fff;
        padding: 10px;
        font-size: 14px;
    }

    td {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        font-size: 14px;
    }

    td.right, th.right {
        text-align: right;
    }

    .summary {
        margin-top: 20px;
        width: 100%;
    }

    .summary td {
        padding: 6px;
        font-size: 14px;
    }

    .summary .total {
        font-size: 18px;
        font-weight: bold;
        border-top: 2px solid #222;
        padding-top: 10px;
    }

    .footer {
        margin-top: 30px;
        text-align: center;
        font-size: 13px;
        color: #555;
    }

    .print-btn {
        text-align: center;
        margin-top: 20px;
    }

    .print-btn button {
        background: #222;
        color: #fff;
        border: none;
        padding: 10px 25px;
        cursor: pointer;
        font-size: 14px;
        border-radius: 4px;
    }

    @media print {
        body {
            background: none;
        }
        .invoice {
            box-shadow: none;
            padding: 0;
        }
        .print-btn {
            display: none;
        }
    }
</style>
</head>

<body>

<div class="invoice">

    <!-- Header -->
    <div class="header">
        <div class="store">
            <h2><?= $store['name'] ?></h2>
            <small>
                <?= $store['address'] ?><br>
                Phone: <?= $store['phone'] ?><br>
                GSTIN: <?= $store['gstin'] ?>
            </small>
        </div>

        <div class="invoice-title">
            <h1>INVOICE</h1>
            <small>
                Invoice #: <?= $invoice['invoice_no'] ?><br>
                Date: <?= $invoice['date'] ?><br>
                Payment: <?= $invoice['payment_mode'] ?>
            </small>
        </div>
    </div>

    <!-- Customer Info -->
    <div class="info">
        <div>
            <strong>Bill To</strong><br>
            <?= $invoice['customer'] ?><br>
            Phone: <?= $invoice['phone'] ?>
        </div>
    </div>

    <!-- Items -->
    <table>
        <tr>
            <th>#</th>
            <th>Item</th>
            <th class="right">Qty</th>
            <th class="right">Rate (₹)</th>
            <th class="right">Amount (₹)</th>
        </tr>

        <?php foreach ($items as $i => $item): ?>
        <tr>
            <td><?= $i + 1 ?></td>
            <td><?= $item['name'] ?></td>
            <td class="right"><?= $item['qty'] ?></td>
            <td class="right"><?= number_format($item['price'], 2) ?></td>
            <td class="right"><?= number_format($item['qty'] * $item['price'], 2) ?></td>
        </tr>
        <?php endforeach; ?>
    </table>

    <!-- Summary -->
    <table class="summary">
        <tr>
            <td class="right" width="80%">Subtotal:</td>
            <td class="right">₹ <?= number_format($subtotal, 2) ?></td>
        </tr>
        <tr>
            <td class="right">CGST (<?= $gst_percent/2 ?>%):</td>
            <td class="right">₹ <?= number_format($cgst, 2) ?></td>
        </tr>
        <tr>
            <td class="right">SGST (<?= $gst_percent/2 ?>%):</td>
            <td class="right">₹ <?= number_format($sgst, 2) ?></td>
        </tr>
        <tr>
            <td class="right">Discount:</td>
            <td class="right">₹ <?= number_format($discount, 2) ?></td>
        </tr>
        <tr class="total">
            <td class="right">Grand Total:</td>
            <td class="right">₹ <?= number_format($grand_total, 2) ?></td>
        </tr>
    </table>

    <div class="footer">
        Thank you for shopping with us! <br>
        <em>Goods once sold will not be taken back.</em>
    </div>

</div>

<div class="print-btn">
    <button onclick="window.print()">🖨️ Print Invoice</button>
</div>

</body>
</html>
