<?php
$pageTitle = 'Purchases';
require_once '../includes/functions.php';
requireLogin();
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);

// Delete purchase
if ($action === 'delete' && $id) {
    try {
        $db->prepare("DELETE FROM purchases WHERE id=?")->execute([$id]);
        setFlash('success', 'Purchase deleted.');
    } catch (PDOException $e) {
        setFlash('error', 'Failed to delete purchase.');
    }
    header('Location: purchases.php');
    exit;
}

// Update status
if ($action === 'status' && $id && isset($_GET['s'])) {
    $validStatuses = ['draft','received','paid','cancelled'];
    $s = $_GET['s'];
    if (in_array($s, $validStatuses)) {
        try {
            $db->prepare("UPDATE purchases SET status=? WHERE id=?")->execute([$s, $id]);
            setFlash('success', 'Purchase status updated.');
        } catch (PDOException $e) {
            setFlash('error', 'Failed to update purchase status.');
        }
    }
    header('Location: purchases.php');
    exit;
}

// Filters
$search     = trim($_GET['search'] ?? '');
$status_f   = trim($_GET['status'] ?? '');
$page       = max(1, (int)($_GET['page'] ?? 1));
$where      = 'WHERE 1=1';
$params     = [];

if ($search) {
    $where .= ' AND (p.purchase_number LIKE ? OR p.supplier_name LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($status_f) {
    $where .= ' AND p.status = ?';
    $params[] = $status_f;
}

// Pagination
$perPage = 25;
$offset  = ($page - 1) * $perPage;
$countStmt = $db->prepare("SELECT COUNT(*) as cnt FROM purchases p $where");
$countStmt->execute($params);
$total   = $countStmt->fetch()['cnt'];
$totalPages = ceil($total / $perPage);

// Fetch purchases
$sql = "
    SELECT p.*,
           (SELECT COUNT(*) FROM purchase_items WHERE purchase_id = p.id) as item_count
    FROM purchases p
    $where
    ORDER BY p.created_at DESC
    LIMIT $perPage OFFSET $offset
";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$purchases = $stmt->fetchAll();

require_once '../includes/header.php';
?>

<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-6">
    <div>
        <h2 class="text-lg font-bold text-slate-800">Purchases</h2>
        <p class="text-sm text-slate-400">Manage purchased products and inventory</p>
    </div>
    <a href="purchase_add.php" class="btn-primary">
        <i class="fas fa-plus mr-1"></i> Add Purchase
    </a>
</div>

<!-- Filters -->
<div class="card p-4 mb-6">
    <form method="GET" class="flex flex-col sm:flex-row gap-4">
        <div class="flex-1">
            <input type="text" name="search" value="<?= sanitize($search) ?>" placeholder="Search by purchase number or supplier..." class="form-input">
        </div>
        <div class="sm:w-48">
            <select name="status" class="form-input">
                <option value="">All Statuses</option>
                <option value="draft" <?= $status_f === 'draft' ? 'selected' : '' ?>>Draft</option>
                <option value="received" <?= $status_f === 'received' ? 'selected' : '' ?>>Received</option>
                <option value="paid" <?= $status_f === 'paid' ? 'selected' : '' ?>>Paid</option>
                <option value="cancelled" <?= $status_f === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
            </select>
        </div>
        <button type="submit" class="btn-primary">Filter</button>
        <?php if ($search || $status_f): ?>
        <a href="purchases.php" class="btn-outline">Clear</a>
        <?php endif; ?>
    </form>
</div>

<!-- Table -->
<div class="card overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-slate-50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase">Purchase #</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase">Supplier</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase">Date</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase">Items</th>
                    <th class="px-6 py-3 text-right text-xs font-semibold text-slate-600 uppercase">Total</th>
                    <th class="px-6 py-3 text-left text-xs font-semibold text-slate-600 uppercase">Status</th>
                    <th class="px-6 py-3 text-center text-xs font-semibold text-slate-600 uppercase">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($purchases)): ?>
                <tr>
                    <td colspan="7" class="px-6 py-8 text-center text-slate-500">
                        <i class="fas fa-shopping-cart text-4xl mb-2 text-slate-300"></i>
                        <p>No purchases found.</p>
                        <a href="purchase_add.php" class="text-brand-600 hover:text-brand-700">Add your first purchase</a>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($purchases as $p): ?>
                <tr class="table-row">
                    <td class="px-6 py-4">
                        <div class="font-semibold text-slate-800"><?= sanitize($p['purchase_number']) ?></div>
                        <div class="text-xs text-slate-500"><?= formatDate($p['created_at']) ?></div>
                    </td>
                    <td class="px-6 py-4">
                        <div class="font-medium text-slate-800"><?= sanitize($p['supplier_name']) ?></div>
                        <?php if ($p['supplier_gstin']): ?>
                        <div class="text-xs text-slate-500">GSTIN: <?= sanitize($p['supplier_gstin']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="px-6 py-4 text-slate-600">
                        <?= formatDate($p['purchase_date']) ?>
                    </td>
                    <td class="px-6 py-4 text-slate-600">
                        <?= (int)$p['item_count'] ?> item(s)
                    </td>
                    <td class="px-6 py-4 text-right font-semibold text-slate-800">
                        ₹<?= number_format($p['total_amount'], 2) ?>
                    </td>
                    <td class="px-6 py-4">
                        <?php
                        $statusClasses = [
                            'draft' => 'bg-slate-100 text-slate-700',
                            'received' => 'bg-green-100 text-green-700',
                            'paid' => 'bg-blue-100 text-blue-700',
                            'cancelled' => 'bg-red-100 text-red-700'
                        ];
                        $statusClass = $statusClasses[$p['status']] ?? 'bg-slate-100 text-slate-700';
                        ?>
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?= $statusClass ?>">
                            <?= ucfirst($p['status']) ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-center">
                        <div class="flex items-center justify-center gap-2">
                            <a href="purchase_view.php?id=<?= $p['id'] ?>" class="text-brand-600 hover:text-brand-700 text-sm" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                            <div class="relative">
                                <button type="button" onclick="toggleStatusMenu(<?= $p['id'] ?>)" class="text-slate-600 hover:text-slate-800 text-sm" title="Change Status">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                                <div id="status-menu-<?= $p['id'] ?>" class="absolute right-0 mt-1 w-32 bg-white border border-slate-200 rounded-lg shadow-lg z-10 hidden">
                                    <a href="?action=status&id=<?= $p['id'] ?>&s=draft" class="block px-3 py-2 text-xs text-slate-700 hover:bg-slate-50">Draft</a>
                                    <a href="?action=status&id=<?= $p['id'] ?>&s=received" class="block px-3 py-2 text-xs text-slate-700 hover:bg-slate-50">Received</a>
                                    <a href="?action=status&id=<?= $p['id'] ?>&s=paid" class="block px-3 py-2 text-xs text-slate-700 hover:bg-slate-50">Paid</a>
                                    <a href="?action=status&id=<?= $p['id'] ?>&s=cancelled" class="block px-3 py-2 text-xs text-slate-700 hover:bg-slate-50">Cancelled</a>
                                </div>
                            </div>
                            <a href="?action=delete&id=<?= $p['id'] ?>" onclick="return confirm('Delete this purchase?')" class="text-red-600 hover:text-red-700 text-sm" title="Delete">
                                <i class="fas fa-trash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div class="px-6 py-4 border-t border-slate-100 flex items-center justify-between">
        <div class="text-sm text-slate-600">
            Showing <?= $offset + 1 ?> to <?= min($offset + $perPage, $total) ?> of <?= $total ?> purchases
        </div>
        <div class="flex gap-1">
            <?php if ($page > 1): ?>
            <a href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_f) ?>" class="px-3 py-1 border border-slate-200 rounded text-sm hover:bg-slate-50">Prev</a>
            <?php endif; ?>
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_f) ?>" class="px-3 py-1 border border-slate-200 rounded text-sm <?= $i === $page ? 'bg-brand-600 text-white border-brand-600' : 'hover:bg-slate-50' ?>"><?= $i ?></a>
            <?php endfor; ?>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status_f) ?>" class="px-3 py-1 border border-slate-200 rounded text-sm hover:bg-slate-50">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
function toggleStatusMenu(id) {
    const menu = document.getElementById('status-menu-' + id);
    // Hide all other menus
    document.querySelectorAll('[id^="status-menu-"]').forEach(m => {
        if (m !== menu) m.classList.add('hidden');
    });
    menu.classList.toggle('hidden');
}

// Close menus when clicking outside
document.addEventListener('click', (e) => {
    if (!e.target.closest('[id^="status-menu-"]') && !e.target.closest('button[onclick*="toggleStatusMenu"]')) {
        document.querySelectorAll('[id^="status-menu-"]').forEach(m => m.classList.add('hidden'));
    }
});
</script>

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