<?php
// Sales Module - Show all POS sales
require_once '../config.php';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Sales</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold">Sales</h1>
            <a href="../index.php" class="btn btn-secondary">Home</a>
        </div>
        <div class="card mb-4">
            <div class="card-header bg-success text-white">New Sale</div>
            <div class="card-body">
                <form class="row g-3">
                    <div class="col-md-4">
                        <input type="text" class="form-control" placeholder="Product Name" disabled>
                    </div>
                    <div class="col-md-2">
                        <input type="number" class="form-control" placeholder="Quantity" disabled>
                    </div>
                    <div class="col-md-2">
                        <input type="number" step="0.01" class="form-control" placeholder="Price" disabled>
                    </div>
                    <div class="col-md-4">
                        <button type="button" class="btn btn-success w-100" disabled>Add Sale</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="card mb-4">
            <div class="card-header bg-light">Filter Sales</div>
            <div class="card-body">
                <form method="get" class="row g-2 align-items-end">
                    <div class="col-md-3">
                        <label for="date_from" class="form-label mb-0">From</label>
                        <input type="date" id="date_from" name="date_from" class="form-control" value="<?= htmlspecialchars($_GET['date_from'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label for="date_to" class="form-label mb-0">To</label>
                        <input type="date" id="date_to" name="date_to" class="form-control" value="<?= htmlspecialchars($_GET['date_to'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <label for="product" class="form-label mb-0">Product</label>
                        <input type="text" id="product" name="product" class="form-control" placeholder="Product name" value="<?= htmlspecialchars($_GET['product'] ?? '') ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="payment" class="form-label mb-0">Payment</label>
                        <select id="payment" name="payment" class="form-select">
                            <option value="">All</option>
                            <option value="cash" <?= (($_GET['payment'] ?? '') === 'cash') ? 'selected' : '' ?>>Cash</option>
                            <option value="card" <?= (($_GET['payment'] ?? '') === 'card') ? 'selected' : '' ?>>Card</option>
                            <option value="voucher" <?= (($_GET['payment'] ?? '') === 'voucher') ? 'selected' : '' ?>>Voucher</option>
                        </select>
                    </div>
                    <div class="col-md-1">
                        <button type="submit" class="btn btn-primary w-100">Filter</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="card mb-4">
            <div class="card-header bg-light">Search Sales</div>
            <div class="card-body">
                <form method="get" class="row g-2 align-items-end">
                    <div class="col-md-6">
                        <input type="text" name="search" class="form-control" placeholder="Search by product name or sale ID" value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-info w-100">Search</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="card">
            <div class="card-header bg-primary text-white">Sales List</div>
            <div class="card-body">
                <form method="get" class="mb-3">
                    <?php foreach ($_GET as $k => $v) {
                        if ($k !== 'export') echo "<input type='hidden' name='".htmlspecialchars($k)."' value='".htmlspecialchars($v)."'>";
                    } ?>
                    <button type="submit" name="export" value="csv" class="btn btn-outline-success">Export to CSV</button>
                </form>
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Sale ID</th>
                            <th>Date</th>
                            <th>Product</th>
                            <th>Quantity</th>
                            <th>Unit Price</th>
                            <th>Total</th>
                            <th>Payment</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    // Build filter conditions
                    $where = [];
                    $params = [];
                    if (!empty($_GET['date_from'])) {
                        $where[] = "DATE(s.sale_date) >= ?";
                        $params[] = $_GET['date_from'];
                    }
                    if (!empty($_GET['date_to'])) {
                        $where[] = "DATE(s.sale_date) <= ?";
                        $params[] = $_GET['date_to'];
                    }
                    if (!empty($_GET['product'])) {
                        $where[] = "p.name LIKE ?";
                        $params[] = '%' . $_GET['product'] . '%';
                    }
                    if (!empty($_GET['payment'])) {
                        $where[] = "s.payment_method = ?";
                        $params[] = $_GET['payment'];
                    }
                    if (!empty($_GET['search'])) {
                        $search = $_GET['search'];
                        $where[] = "(p.name LIKE ? OR s.id = ?)";
                        $params[] = "%$search%";
                        $params[] = $search;
                    }
                    $where_sql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
                    $sql = "SELECT s.id as sale_id, s.sale_date, s.payment_method, si.product_id, p.name as product_name, si.quantity, si.unit_price, si.total_price
                            FROM sales s
                            JOIN sale_items si ON s.id = si.sale_id
                            JOIN products p ON si.product_id = p.id
                            $where_sql
                            ORDER BY s.sale_date DESC, s.id DESC";
                    $stmt = $conn->prepare($sql);
                    if ($params) {
                        $types = str_repeat('s', count($params));
                        $stmt->bind_param($types, ...$params);
                    }
                    $stmt->execute();
                    $result = $stmt->get_result();
                    if (isset($_GET['export']) && $_GET['export'] === 'csv') {
                        header('Content-Type: text/csv');
                        header('Content-Disposition: attachment; filename="sales_export_'.date('Ymd_His').'.csv"');
                        $out = fopen('php://output', 'w');
                        fputcsv($out, ['Sale ID', 'Date', 'Product', 'Quantity', 'Unit Price', 'Total', 'Payment']);
                        if ($result && $result->num_rows > 0) {
                            foreach ($result as $row) {
                                fputcsv($out, [
                                    $row['sale_id'],
                                    $row['sale_date'],
                                    $row['product_name'],
                                    $row['quantity'],
                                    $row['unit_price'],
                                    $row['total_price'],
                                    $row['payment_method']
                                ]);
                            }
                        }
                        fclose($out);
                        exit;
                    }
                    if ($result && $result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            echo '<tr>';
                            echo '<td>' . $row['sale_id'] . '</td>';
                            echo '<td>' . $row['sale_date'] . '</td>';
                            echo '<td>' . htmlspecialchars($row['product_name']) . '</td>';
                            echo '<td>' . $row['quantity'] . '</td>';
                            echo '<td>' . number_format($row['unit_price'], 2) . '</td>';
                            echo '<td>' . number_format($row['total_price'], 2) . '</td>';
                            echo '<td>' . htmlspecialchars($row['payment_method']) . '</td>';
                            echo '<td>';
                            echo '<a class="btn btn-sm btn-outline-primary" href="../pos/receipt.php?id=' . intval($row['sale_id']) . '" target="_blank" title="Reprint receipt">Reprint</a>';
                            echo '</td>';
                            echo '</tr>';
                        }
                    } else {
                        echo '<tr><td colspan="7" class="text-center">No sales found.</td></tr>';
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
