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

$from      = $_GET['from']      ?? date('Y-m-01');
$to        = $_GET['to']        ?? date('Y-m-d');
$vendor_id = $_GET['vendor_id'] ?? '';
$status    = $_GET['status']    ?? 'final';
$itemWise  = isset($_GET['itemwise']) ? 1 : 0;
$search    = trim($_GET['search'] ?? '');

$page   = max(1, intval($_GET['page'] ?? 1));
$limit  = 20;
$offset = ($page - 1) * $limit;

/* Vendors dropdown */
$vendors = $conn->query("SELECT id, name FROM vendors ORDER BY name ASC");

/* WHERE conditions */
$where  = " WHERE po.purchase_date BETWEEN ? AND ? AND po.company_id = ? ";
$params = [$from, $to, $cid];
$types  = "ssi";

if ($status !== 'all') {
    $where .= " AND po.status = ? ";
    $params[] = $status;
    $types .= "s";
}

if (!empty($vendor_id)) {
    $where .= " AND po.vendor_id = ? ";
    $params[] = $vendor_id;
    $types .= "i";
}

if (!empty($search)) {
    $where .= " AND (po.po_no LIKE ? OR v.name LIKE ? OR po.supplier_invoice_no LIKE ?) ";
    $like = "%$search%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= "sss";
}

/* Count total rows */
$countSql = "
    SELECT COUNT(*) as total
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    $where
";
$stmtCount = $conn->prepare($countSql);
$stmtCount->bind_param($types, ...$params);
$stmtCount->execute();
$totalRows = $stmtCount->get_result()->fetch_assoc()['total'] ?? 0;

$totalPages = ceil($totalRows / $limit);

/* Fetch purchase orders */
$sql = "
    SELECT po.*, v.name AS vendor_name
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    $where
    ORDER BY po.id DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

/* If itemwise enabled, preload items grouped by purchase_order_id */
$itemsByPO = [];

if ($itemWise && $result->num_rows > 0) {
    $poIds = [];
    $rowsTemp = [];
    while ($row = $result->fetch_assoc()) {
        $rowsTemp[] = $row;
        $poIds[] = $row['id'];
    }
    $resultRows = $rowsTemp;
    $inIds = implode(",", array_map("intval", $poIds));
    $itemSql = "
        SELECT pi.*, p.name AS product_name, p.brand, p.hsn_code, p.unit
        FROM purchase_items pi
        JOIN products p ON p.id = pi.product_id
        WHERE pi.purchase_order_id IN ($inIds)
        ORDER BY pi.purchase_order_id DESC, pi.id ASC
    ";
    $itemRes = $conn->query($itemSql);
    while ($it = $itemRes->fetch_assoc()) {
        $itemsByPO[$it['purchase_order_id']][] = $it;
    }
} else {
    $resultRows = [];
    while ($row = $result->fetch_assoc()) {
        $resultRows[] = $row;
    }
}
?>

<div class="page-header">
    <h2><i class="fas fa-shopping-cart" style="color:var(--primary);margin-right:8px;"></i>Purchase Report</h2>
    <div style="display:flex;gap:8px;">
        <a href="purchase_export_excel.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&vendor_id=<?= urlencode($vendor_id) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>&itemwise=<?= $itemWise ?>"
           target="_blank" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Excel</a>
        <a href="purchase_export_pdf.php?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&vendor_id=<?= urlencode($vendor_id) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>&itemwise=<?= $itemWise ?>"
           target="_blank" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> PDF</a>
    </div>
</div>

<!-- Filters -->
<div class="filter-panel">
    <form method="GET" class="filter-form">
        <div class="filter-group">
            <label>From</label>
            <input type="date" name="from" value="<?= htmlspecialchars($from) ?>">
        </div>
        <div class="filter-group">
            <label>To</label>
            <input type="date" name="to" value="<?= htmlspecialchars($to) ?>">
        </div>
        <div class="filter-group">
            <label>Status</label>
            <select name="status">
                <option value="final" <?= $status==='final'?'selected':'' ?>>Finalized</option>
                <option value="draft" <?= $status==='draft'?'selected':'' ?>>Draft</option>
                <option value="all"   <?= $status==='all'  ?'selected':'' ?>>All</option>
            </select>
        </div>
        <div class="filter-group">
            <label>Vendor</label>
            <select name="vendor_id">
                <option value="">All Vendors</option>
                <?php while($v = $vendors->fetch_assoc()): ?>
                    <option value="<?= $v['id'] ?>" <?= ($vendor_id==$v['id'])?'selected':'' ?>>
                        <?= htmlspecialchars($v['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="filter-group" style="flex:1;min-width:220px;">
            <label>Search</label>
            <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="PO No / Vendor / Supplier Invoice">
        </div>
        <div class="filter-group" style="justify-content:flex-end;">
            <label style="font-weight:400;text-transform:none;letter-spacing:0;display:flex;align-items:center;gap:6px;margin-top:20px;cursor:pointer;">
                <input type="checkbox" name="itemwise" value="1" <?= $itemWise ? 'checked' : '' ?> style="width:auto;accent-color:var(--primary);">
                Item Wise
            </label>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Filter</button>
            <a href="purchase_report.php" class="btn btn-secondary">Reset</a>
        </div>
    </form>
</div>

<!-- Table -->
<div class="panel">
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>PO No</th>
                    <th>Supplier Invoice</th>
                    <th>Date</th>
                    <th>Vendor</th>
                    <th>Status</th>
                    <th style="text-align:right;">Total</th>
                    <th style="text-align:right;">GST</th>
                    <th style="text-align:right;">Net</th>
                    <?php if($itemWise): ?>
                        <th style="text-align:center;">Items</th>
                    <?php endif; ?>
                </tr>
            </thead>
            <tbody>
            <?php if(count($resultRows) > 0): ?>
                <?php foreach($resultRows as $row): ?>
                <tr>
                    <td><a href="#" onclick="openDocPopup('purchase',<?= $row['id'] ?>,'<?= htmlspecialchars($row['po_no'],ENT_QUOTES) ?>');return false;" style="font-weight:700;color:var(--primary);text-decoration:none;"><?= htmlspecialchars($row['po_no']) ?></a></td>
                    <td style="color:var(--text-secondary);"><?= htmlspecialchars($row['supplier_invoice_no'] ?? '-') ?></td>
                    <td><?= date('d-m-Y', strtotime($row['purchase_date'])) ?></td>
                    <td><?= htmlspecialchars($row['vendor_name']) ?></td>
                    <td>
                        <span class="badge <?= $row['status']==='final' ? 'badge-success' : 'badge-warning' ?>">
                            <?= ucfirst($row['status']) ?>
                        </span>
                    </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>
                    <?php if($itemWise): ?>
                    <td style="text-align:center;">
                        <button type="button" class="action-btn view" onclick="toggleItems(<?= $row['id'] ?>)" title="Toggle Items">
                            <i class="fas fa-list"></i>
                        </button>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php if($itemWise): ?>
                <tr id="itemsRow<?= $row['id'] ?>" style="display:none;">
                    <td colspan="9" style="padding:0;background:var(--content-bg);">
                        <div style="padding:12px 16px;">
                            <table style="font-size:13px;width:100%;border-collapse:collapse;">
                                <thead>
                                    <tr style="background:var(--primary);color:#fff;">
                                        <th style="padding:6px 10px;text-align:left;">Product</th>
                                        <th style="padding:6px 10px;text-align:left;">Brand</th>
                                        <th style="padding:6px 10px;text-align:left;">HSN</th>
                                        <th style="padding:6px 10px;text-align:left;">Unit</th>
                                        <th style="padding:6px 10px;text-align:left;">Batch</th>
                                        <th style="padding:6px 10px;text-align:right;">MRP</th>
                                        <th style="padding:6px 10px;text-align:right;">Purchase</th>
                                        <th style="padding:6px 10px;text-align:right;">Selling</th>
                                        <th style="padding:6px 10px;text-align:center;">Qty</th>
                                        <th style="padding:6px 10px;text-align:center;">Avail</th>
                                        <th style="padding:6px 10px;text-align:center;">GST%</th>
                                        <th style="padding:6px 10px;text-align:left;">Expiry</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php
                                $items = $itemsByPO[$row['id']] ?? [];
                                if(count($items) > 0):
                                    foreach($items as $it):
                                ?>
                                <tr style="border-bottom:1px solid var(--border);">
                                    <td style="padding:6px 10px;"><?= htmlspecialchars($it['product_name']) ?></td>
                                    <td style="padding:6px 10px;"><?= htmlspecialchars($it['brand']) ?></td>
                                    <td style="padding:6px 10px;"><?= htmlspecialchars($it['hsn_code']) ?></td>
                                    <td style="padding:6px 10px;"><?= htmlspecialchars($it['unit']) ?></td>
                                    <td style="padding:6px 10px;"><?= htmlspecialchars($it['batch_no']) ?></td>
                                    <td style="padding:6px 10px;text-align:right;">&#8377; <?= number_format($it['mrp'], 2) ?></td>
                                    <td style="padding:6px 10px;text-align:right;">&#8377; <?= number_format($it['purchase_price'], 2) ?></td>
                                    <td style="padding:6px 10px;text-align:right;">&#8377; <?= number_format($it['selling_price'], 2) ?></td>
                                    <td style="padding:6px 10px;text-align:center;"><?= number_format($it['quantity'], 0) ?></td>
                                    <td style="padding:6px 10px;text-align:center;"><?= number_format($it['available_qty'], 0) ?></td>
                                    <td style="padding:6px 10px;text-align:center;"><?= number_format($it['gst_percent'], 2) ?>%</td>
                                    <td style="padding:6px 10px;"><?= !empty($it['expiry_date']) ? date('d-m-Y', strtotime($it['expiry_date'])) : '-' ?></td>
                                </tr>
                                <?php endforeach; else: ?>
                                <tr><td colspan="12" style="padding:12px;text-align:center;color:var(--text-muted);">No items found.</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="<?= $itemWise ? 9 : 8 ?>" style="text-align:center;padding:40px;color:var(--text-muted);">No purchases found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Pagination -->
<?php if($totalPages > 1): ?>
<div style="display:flex;justify-content:center;gap:4px;margin-top:16px;flex-wrap:wrap;">
    <?php for($p=1; $p<=$totalPages; $p++): ?>
        <a style="padding:6px 12px;border:1px solid var(--border);border-radius:6px;text-decoration:none;font-size:13px;
                  <?= ($p==$page) ? 'background:var(--primary);color:#fff;border-color:var(--primary);font-weight:600;' : 'color:var(--text-primary);' ?>"
           href="?from=<?= urlencode($from) ?>&to=<?= urlencode($to) ?>&vendor_id=<?= urlencode($vendor_id) ?>&status=<?= urlencode($status) ?>&search=<?= urlencode($search) ?>&itemwise=<?= $itemWise ?>&page=<?= $p ?>">
            <?= $p ?>
        </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<script>
function toggleItems(poId) {
    const row = document.getElementById("itemsRow" + poId);
    row.style.display = (row.style.display === "none") ? "table-row" : "none";
}
</script>

<?php require_once '../includes/doc_popup_modal.php'; ?>
<?php require_once '../includes/footer.php'; ?>
