<?php
require_once '../includes/auth.php';
requirePermission('purchases', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$userRole = $_SESSION['user_role'] ?? '';

$filterCo = $cid;
$companies = null;
if ($userRole === 'admin') {
    $filterCo  = isset($_GET['co']) ? (int)$_GET['co'] : $cid;
    $companies = $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name");
}

$coWhere = $filterCo > 0 ? "AND po.company_id = $filterCo" : "";

// Ensure payment columns exist
$existingCols = array_column(
    $conn->query("SHOW COLUMNS FROM purchase_orders")->fetch_all(MYSQLI_ASSOC), 'Field'
);
if (!in_array('received_amount', $existingCols))
    $conn->query("ALTER TABLE purchase_orders ADD COLUMN received_amount DECIMAL(12,2) NOT NULL DEFAULT 0");
if (!in_array('balance_amount', $existingCols))
    $conn->query("ALTER TABLE purchase_orders ADD COLUMN balance_amount DECIMAL(12,2) NOT NULL DEFAULT 0");

// Initialize balance for POs where it defaulted to 0 but hasn't been set yet
$conn->query("UPDATE purchase_orders SET balance_amount = net_amount - received_amount WHERE balance_amount = 0 AND received_amount = 0 AND net_amount > 0");

$result = $conn->query("
    SELECT po.id, po.po_no, po.purchase_date, po.status,
           po.total_amount, po.gst_amount, po.net_amount,
           po.received_amount, po.balance_amount,
           po.supplier_invoice_no,
           v.name AS vendor_name
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    WHERE 1=1 $coWhere
    ORDER BY po.purchase_date DESC
");
?>

<div class="page-header">
    <h2><i class="fas fa-file-invoice" style="color:var(--primary);margin-right:8px;"></i>Purchase Orders</h2>
    <div style="display:flex;gap:8px;">
        <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Purchase</a>
        <a href="create_ai.php" class="btn btn-outline" style="color:var(--primary);border-color:var(--primary);"><i class="fas fa-magic"></i> New Purchase via AI</a>
    </div>
</div>

<?php if ($userRole === 'admin' && $companies): ?>
<div class="panel" style="margin-bottom:14px;">
    <div class="panel-body" style="padding:10px 16px;">
        <form method="get" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
            <label style="font-size:13px;font-weight:600;color:var(--text-secondary);margin:0;">Company:</label>
            <select name="co" onchange="this.form.submit()" style="font-size:13px;padding:5px 10px;border:1px solid var(--border);border-radius:6px;">
                <option value="0" <?= $filterCo == 0 ? 'selected' : '' ?>>All Companies</option>
                <?php while ($co = $companies->fetch_assoc()): ?>
                <option value="<?= $co['id'] ?>" <?= $filterCo == $co['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($co['company_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
            <?php if ($filterCo != $cid): ?>
            <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>
<?php endif; ?>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">All Purchase Orders</span>
        <div style="display:flex;gap:8px;align-items:center;">
            <div style="position:relative;">
                <i class="fas fa-search" style="position:absolute;left:8px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-size:12px;pointer-events:none;"></i>
                <input type="text" id="pgSearch" placeholder="Search PO, vendor..."
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:200px;">
            </div>
            <select id="pgPerPage" style="padding:5px 8px;font-size:12px;border:1px solid var(--border);border-radius:6px;">
                <option value="10">10 / page</option>
                <option value="25" selected>25 / page</option>
                <option value="50">50 / page</option>
                <option value="100">100 / page</option>
                <option value="500">500 / page</option>
            </select>
        </div>
    </div>
    <div style="overflow-x:auto;">
        <table id="mainTable">
            <thead>
                <tr>
                    <th>PO No</th>
                    <th>Date</th>
                    <th>Vendor</th>
                    <th>Supplier Inv No</th>
                    <th style="text-align:right;">Taxable</th>
                    <th style="text-align:right;">GST</th>
                    <th style="text-align:right;">Net Total</th>
                    <th style="text-align:right;">Paid</th>
                    <th style="text-align:right;">Balance</th>
                    <th>Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()):
                    $ds = strtolower($row['po_no'].' '.$row['vendor_name'].' '.$row['purchase_date'].' '.$row['status'].' '.($row['supplier_invoice_no'] ?? ''));
                    $balance = (float)$row['balance_amount'];
                    $paid    = (float)$row['received_amount'];
                ?>
                <tr data-search="<?= htmlspecialchars($ds) ?>" data-id="<?= $row['id'] ?>">
                    <td><strong><?= htmlspecialchars($row['po_no']) ?></strong></td>
                    <td><?= htmlspecialchars($row['purchase_date']) ?></td>
                    <td><?= htmlspecialchars($row['vendor_name']) ?></td>
                    <td style="color:var(--text-secondary);font-size:12px;"><?= htmlspecialchars($row['supplier_invoice_no'] ?: '—') ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['total_amount'], 2) ?></td>
                    <td style="text-align:right;">&#8377; <?= number_format($row['gst_amount'], 2) ?></td>
                    <td style="text-align:right;"><strong>&#8377; <?= number_format($row['net_amount'], 2) ?></strong></td>
                    <td class="td-paid" style="text-align:right;color:var(--success);">&#8377; <?= number_format($paid, 2) ?></td>
                    <td class="td-balance" style="text-align:right;font-weight:600;color:<?= $balance > 0 ? 'var(--danger)' : 'var(--success)' ?>;">&#8377; <?= number_format($balance, 2) ?></td>
                    <td>
                        <?php
                        $s = strtolower($row['status']);
                        $bc = $s === 'final' ? 'badge-success' : ($s === 'draft' ? 'badge-warning' : 'badge-gray');
                        ?>
                        <span class="badge <?= $bc ?>"><?= ucfirst($s) ?></span>
                    </td>
                    <td>
                        <div class="action-links" style="justify-content:center;">
                            <?php if ($row['status'] === 'draft'): ?>
                                <a href="edit.php?id=<?= $row['id'] ?>" class="action-btn edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="delete.php?id=<?= $row['id'] ?>"
                                   onclick="return confirm('Delete this draft purchase?')"
                                   class="action-btn delete" title="Delete">
                                    <i class="fas fa-trash-alt"></i>
                                </a>
                            <?php else: ?>
                                <span class="badge badge-gray" style="font-size:11px;"><i class="fas fa-lock"></i></span>
                                <a href="../purchase_returns/create.php?po_no=<?= urlencode($row['po_no']) ?>" class="action-btn return" title="Purchase Return">
                                    <i class="fas fa-undo"></i>
                                </a>
                                <a href="javascript:void(0)"
                                   onclick="openPurchasePaymentModal(<?= $row['id'] ?>, '<?= htmlspecialchars($row['po_no'], ENT_QUOTES) ?>', '<?= date('d-m-Y', strtotime($row['purchase_date'])) ?>')"
                                   class="action-btn" style="color:var(--primary);" title="Payment Ledger">
                                    <i class="fas fa-receipt"></i>
                                </a>
                            <?php endif; ?>
                            <a href="view.php?id=<?= $row['id'] ?>" class="action-btn view" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="11" style="text-align:center;padding:40px;color:var(--text-muted);">
                        <i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;"></i>
                        No purchase orders found.
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <div id="pgBar" class="pg-bar"></div>
</div>

<style>
.pg-bar{display:flex;align-items:center;gap:8px;padding:8px 16px;border-top:1px solid var(--border,#e2e8f0);flex-wrap:wrap;background:#fafafa;border-radius:0 0 8px 8px}
.pg-info{font-size:13px;color:var(--text-muted,#94a3b8)}
.pg-btns{display:flex;gap:3px;margin-left:auto}
.pg-btns button{padding:3px 9px;font-size:12px;border:1px solid var(--border,#e2e8f0);border-radius:4px;background:#fff;cursor:pointer;min-width:32px}
.pg-btns button:disabled{opacity:.4;cursor:not-allowed}
.pg-btns button.active{background:var(--primary,#2563eb);color:#fff;border-color:var(--primary,#2563eb);font-weight:600}
</style>
<script>
(function(){
    const rows=Array.from(document.querySelectorAll('#mainTable tbody tr[data-search]'));
    const searchEl=document.getElementById('pgSearch');
    const perPageEl=document.getElementById('pgPerPage');
    const barEl=document.getElementById('pgBar');
    let page=1;
    function getVis(){const q=(searchEl?.value||'').trim().toLowerCase();return q?rows.filter(r=>(r.dataset.search||'').includes(q)):rows;}
    function render(){
        const pp=parseInt(perPageEl?.value||25);
        const vis=getVis();const total=vis.length;
        const pages=Math.max(1,Math.ceil(total/pp));
        if(page>pages)page=pages;
        rows.forEach(r=>r.style.display='none');
        const start=(page-1)*pp;
        vis.slice(start,start+pp).forEach(r=>r.style.display='');
        const s=Math.max(1,page-2),e=Math.min(pages,page+2);
        let html=`<span class="pg-info">Showing ${total===0?0:start+1}–${Math.min(start+pp,total)} of ${total} records</span><div class="pg-btns">`;
        html+=`<button onclick="pgGo(1)" ${page<=1?'disabled':''}>«</button>`;
        html+=`<button onclick="pgGo(${page-1})" ${page<=1?'disabled':''}>‹</button>`;
        for(let i=s;i<=e;i++)html+=`<button onclick="pgGo(${i})" ${i===page?'class="active"':''}>${i}</button>`;
        html+=`<button onclick="pgGo(${page+1})" ${page>=pages?'disabled':''}>›</button>`;
        html+=`<button onclick="pgGo(${pages})" ${page>=pages?'disabled':''}>»</button></div>`;
        barEl.innerHTML=html;
    }
    window.pgGo=function(p){page=parseInt(p);render();};
    searchEl?.addEventListener('input',function(){page=1;render();});
    perPageEl?.addEventListener('change',function(){page=1;render();});
    render();
})();
</script>

<script>
window._ppmAfterPaymentChange = function(received, balance) {
    if (!_ppmRow) return;
    const paidCell    = _ppmRow.querySelector('.td-paid');
    const balanceCell = _ppmRow.querySelector('.td-balance');
    if (paidCell)    paidCell.innerHTML    = '&#8377; ' + parseFloat(received).toFixed(2);
    if (balanceCell) {
        balanceCell.innerHTML = '&#8377; ' + parseFloat(balance).toFixed(2);
        balanceCell.style.color = parseFloat(balance) > 0 ? 'var(--danger)' : 'var(--success)';
    }
};
</script>
<?php require_once '../includes/purchase_payment_modal.php'; ?>
<?php require_once '../includes/footer.php'; ?>
