<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

$user_id = (int)($_SESSION['user_id']);
$role    = $_SESSION['role'] ?? 'user';

function e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function money($v) {
    return number_format((float)$v, 2);
}

$bill_id = (int)($_GET['id'] ?? 0);
if ($bill_id <= 0) {
    die('Invalid bill ID');
}

if ($role === 'admin') {
    $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ?");
    $stmt->bind_param("i", $bill_id);
} else {
    $stmt = $conn->prepare("SELECT * FROM bills WHERE id = ? AND created_by = ?");
    $stmt->bind_param("ii", $bill_id, $user_id);
}

$stmt->execute();
$bill = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$bill) {
    die('Bill not found');
}

$stmt = $conn->prepare("SELECT * FROM bill_items WHERE bill_id = ? ORDER BY id ASC");
$stmt->bind_param("i", $bill_id);
$stmt->execute();
$items_result = $stmt->get_result();
$items = [];
while ($row = $items_result->fetch_assoc()) {
    $items[] = $row;
}
$stmt->close();

$bill_no   = 'BILL-' . (int)$bill['id'];
$status    = $bill['payment_status'] ?? 'unpaid';
$created   = !empty($bill['created_at']) ? date('Y-m-d', strtotime($bill['created_at'])) : '-';
$due_date  = !empty($bill['unpaid_due_date']) ? date('Y-m-d', strtotime($bill['unpaid_due_date'])) : (!empty($bill['due_date']) ? date('Y-m-d', strtotime($bill['due_date'])) : '-');

$subtotal  = (float)($bill['subtotal'] ?? $bill['taxable_amount'] ?? 0);
$discount  = (float)($bill['discount_amount'] ?? 0);
$taxable   = (float)($bill['taxable_amount'] ?? 0);
$sgst_tot  = (float)($bill['sgst_amount'] ?? 0);
$cgst_tot  = (float)($bill['cgst_amount'] ?? 0);
$grand_tot = (float)($bill['total_amount'] ?? 0);
$paid_amount   = (float)($bill['advance_amount'] ?? 0);
$pending_amount = (float)($bill['due_amount'] ?? ($grand_tot - $paid_amount));
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Invoice - <?php echo e($bill_no); ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root{
        --bg:#f4f6fb;
        --card:#ffffff;
        --text:#0f172a;
        --muted:#64748b;
        --line:#e5e7eb;
        --head1:#34495f;
        --head2:#2c4b6c;
        --accent:#ef4444;
        --accent-bg:#ffe7e7;
        --btn:#334155;
        --btn-text:#ffffff;
        --green:#16a34a;
    }
    *{box-sizing:border-box}
    body{
        margin:0;
        background:var(--bg);
        font-family:Arial, Helvetica, sans-serif;
        color:var(--text);
    }
    .page{
        max-width:1280px;
        margin:0 auto;
        padding:10px;
    }
    .sheet{
        background:var(--card);
        border-radius:18px;
        box-shadow:0 8px 24px rgba(15,23,42,.08);
        padding:26px 26px 18px;
        min-height:calc(100vh - 20px);
    }
    .top{
        display:flex;
        justify-content:space-between;
        align-items:flex-start;
        gap:20px;
        flex-wrap:wrap;
    }
    .brand{
        min-width:240px;
    }
    .brand h1{
        margin:0;
        font-size:44px;
        line-height:1;
        font-weight:800;
        color:#223b57;
        letter-spacing:-.03em;
    }
    .brand .sub{
        margin-top:6px;
        font-size:18px;
        color:#415a77;
    }
    .brand .meta{
        margin-top:2px;
        font-size:16px;
        color:#516b8a;
    }
    .status-wrap{
        flex:1;
        display:flex;
        justify-content:center;
        align-items:flex-start;
        padding-top:6px;
        min-width:160px;
    }
    .status{
        padding:10px 24px;
        border-radius:999px;
        background:var(--accent-bg);
        color:var(--accent);
        font-size:22px;
        font-weight:800;
        border:1px solid #ffb5b5;
        box-shadow:0 1px 0 rgba(0,0,0,.03);
    }
    .right{
        min-width:220px;
        text-align:right;
        color:#38506a;
        font-size:16px;
        line-height:1.35;
    }
    .right .billno{
        font-size:20px;
        font-weight:800;
        color:#5b6777;
    }
    .divider{
        height:1px;
        background:var(--line);
        margin:18px 0 24px;
    }
    .section-title{
        font-size:22px;
        font-weight:800;
        color:#223b57;
        margin:0 0 12px;
    }
    .table-wrap{
        overflow:auto;
        border-radius:12px;
        border:1px solid var(--line);
    }
    table{
        width:100%;
        border-collapse:separate;
        border-spacing:0;
        min-width:1050px;
    }
    thead th{
        background:linear-gradient(180deg, var(--head1), var(--head2));
        color:#fff;
        text-align:left;
        padding:15px 12px;
        font-size:18px;
        font-weight:700;
        white-space:nowrap;
    }
    thead th:first-child{
        border-top-left-radius:12px;
    }
    thead th:last-child{
        border-top-right-radius:12px;
    }
    tbody td{
        padding:15px 12px;
        border-bottom:1px solid #edf1f5;
        background:#fff;
        vertical-align:top;
        font-size:17px;
    }
    tbody tr:last-child td{
        border-bottom:none;
    }
    .prod{
        font-weight:400;
    }
    .prod small{
        display:block;
        margin-top:4px;
        color:#6b7280;
        font-size:14px;
    }
    .totals{
        display:flex;
        justify-content:flex-end;
        margin-top:28px;
    }
    .totals-inner{
        width:min(420px, 100%);
        font-size:18px;
    }
    .totals-row{
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:20px;
        padding:8px 0;
    }
    .totals-row .label{
        font-weight:800;
        color:#12213a;
    }
    .totals-row .value{
        min-width:140px;
        text-align:right;
        font-weight:500;
    }
    .totals-row.discount .value{
        color:var(--green);
    }
    .totals-row.grand{
        padding-top:12px;
        margin-top:6px;
        border-top:1px solid var(--line);
        font-size:19px;
    }
    .totals-row.grand .value{
        font-weight:900;
        font-size:21px;
    }
    .footer-note{
        text-align:center;
        color:#6b7c93;
        font-size:18px;
        margin:34px 0 24px;
    }
    .actions{
        display:flex;
        justify-content:flex-end;
        gap:10px;
        flex-wrap:wrap;
        margin-top:10px;
    }
    .btn{
        border:none;
        border-radius:26px;
        padding:14px 20px;
        text-decoration:none;
        display:inline-flex;
        align-items:center;
        gap:10px;
        font-size:18px;
        font-weight:800;
        cursor:pointer;
        box-shadow:0 1px 0 rgba(0,0,0,.04);
    }
    .btn.back{
        background:#e5e7eb;
        color:#111827;
    }
    .btn.dark{
        background:var(--btn);
        color:var(--btn-text);
    }
    .btn.dark:hover,
    .btn.back:hover{
        opacity:.95;
    }
    .btn .icon-box{
        display:inline-flex;
        align-items:center;
        justify-content:center;
        width:22px;
    }
.status.paid{
    background:#e7f8ee;
    color:#16a34a;
    border:1px solid #86efac;
}
.status.unpaid{
    background:#ffe7e7;
    color:#ef4444;
}
.status.advance{
    background:#fff7e6;
    color:#f59e0b;
}
    @media print{
        body{background:#fff}
        .page{padding:0}
        .sheet{
            box-shadow:none;
            border-radius:0;
            min-height:auto;
            padding:18px;
        }
        .actions{display:none}
    }
    @media (max-width: 900px){
        .top{gap:14px}
        .brand h1{font-size:34px}
        .right{text-align:left}
        .status-wrap{justify-content:flex-start}
        .totals{justify-content:stretch}
        .totals-inner{width:100%}
    }
</style>
</head>
<body>
<div class="page">
    <div class="sheet">
        <div class="top">
            <div class="brand">
                <h1><?php echo e($bill['customer_name'] ?? 'Customer'); ?></h1>
                <div class="sub"><?php echo e($bill['address'] ?? ''); ?></div>
                <div class="meta">
                    GST: <?php echo e($bill['customer_gst'] ?? '-'); ?> |
                    Phone: <?php echo e($bill['phone'] ?? '-'); ?>
                </div>
            </div>

            <div class="status 
<?php 
    if ($paid_amount > 0 && $pending_amount > 0) echo 'advance';
    elseif ($pending_amount <= 0) echo 'paid';
    else echo 'unpaid';
?>">
<?php 
    if ($paid_amount > 0 && $pending_amount > 0) {
        echo "Advance";
    } elseif ($pending_amount <= 0) {
        echo "Paid";
    } else {
        echo "Unpaid";
    }
?>
</div>

            <div class="right">
                <div class="billno">Bill No #<?php echo e($bill_no); ?></div>
                <div>Date: <?php echo e($created); ?></div>
                <div>Due Date: <?php echo e($due_date); ?></div>
                <div>Customer: <?php echo e($bill['customer_name'] ?? '-'); ?></div>
                <div>Phone: <?php echo e($bill['phone'] ?? '-'); ?></div>
            </div>
        </div>

        <div class="divider"></div>

        <div class="section-title">Items</div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Unit Price</th>
                        <th>Qty</th>
                        <th>Price</th>
                        <th>SGST%</th>
                        <th>CGST%</th>
                        <th>DISCOUNT%</th>
                           <th>Total (incl. tax)</th>
                         <th>Paid</th>
                        <th>
    <?php echo ($paid_amount > 0 && $pending_amount > 0) ? 'Advance' : 'Unpaid'; ?>
</th>
                     
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($items)): ?>
                        <?php foreach ($items as $item): ?>
                            <?php
                                $name    = $item['product_name'] ?? ($item['item_name'] ?? '-');
                                $sku     = $item['sku'] ?? ($item['product_code'] ?? '');
                                $unit    = (float)($item['unit_price'] ?? $item['rate'] ?? 0);
                                $qty     = (float)($item['qty'] ?? 0);
                            $price = (float)($item['price'] ?? ($unit * $qty));

$disc  = (float)($item['discount_percent'] ?? 0);

// Discount
$discount_amount = ($price * $disc) / 100;

// Taxable
$taxable_item = $price - $discount_amount;

// ✅ FIX: GST from bill (not item)
$total_bill_tax = $sgst_tot + $cgst_tot;

// avoid divide by zero
$gst_percent = $subtotal > 0 ? ($total_bill_tax / $subtotal) * 100 : 0;

// split into SGST / CGST
$sgst = $gst_percent / 2;
$cgst = $gst_percent / 2;

// GST amount
$gst_total = $taxable_item * ($gst_percent / 100);

// final
$totalIt = $taxable_item + $gst_total;
                            ?>
                            <tr>
                                <td class="prod">
                                    <?php echo e($name); ?>
                                    <?php if ($sku !== ''): ?>
                                        <small><?php echo e($sku); ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo e(money($unit)); ?></td>
                                <td><?php echo e($qty); ?></td>
                                <td><?php echo e(money($price)); ?></td>
                                <td><?php echo e(number_format($sgst, 2)); ?></td>
                                <td><?php echo e(number_format($cgst, 2)); ?></td>
                                <td><?php echo e(number_format($disc, 2)); ?></td>
                                <td><?php echo e(money($totalIt)); ?></td>
                                <?php
// total bill level data
$total_bill = $grand_tot;
$paid_bill  = $paid_amount;
$pending_bill = $pending_amount;

// proportion item wise
$ratio = $total_bill > 0 ? ($totalIt / $total_bill) : 0;

$item_paid   = $paid_bill * $ratio;
$item_unpaid = $pending_bill * $ratio;
?>

<td style="color:green;">
    <?php echo e(money($item_paid)); ?>
</td>

<td style="color:red;">
    <?php echo e(money($item_unpaid)); ?>
</td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" style="text-align:center;color:#64748b;">No items found</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="totals">
            <div class="totals-inner">
                <div class="totals-row">
                    <div class="label">Subtotal :</div>
                    <div class="value"><?php echo e(money($subtotal)); ?></div>
                </div>
                <div class="totals-row discount">
                    <div class="label">Discount :</div>
                    <div class="value">-<?php echo e(money($discount)); ?></div>
                </div>
                <div class="totals-row">
                    <div class="label">Taxable Amount :</div>
                    <div class="value"><?php echo e(money($taxable)); ?></div>
                </div>
           
                <div class="totals-row">
                    <div class="label">SGST Total :</div>
                    <div class="value"><?php echo e(money($sgst_tot)); ?></div>
                </div>
                <div class="totals-row">
                    <div class="label">CGST Total :</div>
                    <div class="value"><?php echo e(money($cgst_tot)); ?></div>
                </div>
                <div class="totals-row grand">
                    <div class="label">Grand Total :</div>
                    <div class="value"><?php echo e(money($grand_tot)); ?></div>
                </div>
            </div>
        </div>

        <div class="footer-note">
            Thank you for your purchase! This is a system generated invoice.
        </div>

        <div class="actions">
            <a href="admin_due_alert.php" class="btn back"><span class="icon-box"><i class="fa-solid fa-arrow-left"></i></span> Back</a>
            <a href="javascript:window.print()" class="btn dark"><span class="icon-box"><i class="fa-solid fa-print"></i></span> Print / Save</a>
<a href="#" onclick="downloadPDF()" class="btn dark">
    <i class="fa-regular fa-file-pdf"></i> Download PDF
</a>        </div>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<script>
function downloadPDF() {

    // ❌ hide buttons
    const actions = document.querySelector('.actions');
    if(actions) actions.style.display = 'none';

    const element = document.querySelector('.sheet');

    html2pdf()
        .from(element)
        .set({
            margin: 5,
            filename: 'invoice.pdf',
            html2canvas: { scale: 2 },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        })
        .save()
        .then(() => {
            // ✅ show back after download
            if(actions) actions.style.display = 'flex';
        });
}
</script>
</body>
</html>