<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';

// ================= DEFAULT TODAY =================
$today = date('Y-m-d');

$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$method    = $_GET['method'] ?? '';
$outlet    = $_GET['outlet'] ?? '';
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where_sales = [];
$where_payments = [];

if($from_date){
    $where_sales[] = "DATE(sales_date) >= '".$conn->real_escape_string($from_date)."'";
    $where_payments[] = "DATE(payment_date) >= '".$conn->real_escape_string($from_date)."'";
}
if($to_date){
    $where_sales[] = "DATE(sales_date) <= '".$conn->real_escape_string($to_date)."'";
    $where_payments[] = "DATE(payment_date) <= '".$conn->real_escape_string($to_date)."'";
}
if($method){
    $where_sales[] = "payment_method = '".$conn->real_escape_string($method)."'";
    $where_payments[] = "type = '".$conn->real_escape_string($method)."'";
}
if($outlet !== ''){
    $where_sales[] = "rest = '".$conn->real_escape_string($outlet)."'";
}
if($search){
    $s = $conn->real_escape_string($search);
    $where_sales[] = "(customer_id LIKE '%$s%' OR created_by LIKE '%$s%')";
    $where_payments[] = "(reference LIKE '%$s%' OR received_by LIKE '%$s%')";
}

$where_sales_sql = $where_sales ? "WHERE ".implode(" AND ", $where_sales) : "";
$where_payments_sql = $where_payments ? "WHERE ".implode(" AND ", $where_payments) : "";

// ================= FETCH SALES =================
$sales = $conn->query("SELECT * FROM sales $where_sales_sql ORDER BY sales_date DESC");
$summary_sales = $conn->query("
    SELECT 
        COUNT(*) AS total_count,
        IFNULL(SUM(total),0) AS total_amount,
        IFNULL(SUM(CASE WHEN payment_method='Cash' THEN total END),0) AS cash_total,
        IFNULL(SUM(CASE WHEN payment_method='Card' THEN total END),0) AS card_total,
        IFNULL(SUM(CASE WHEN payment_method='Transfer' THEN total END),0) AS transfer_total
    FROM sales
    $where_sales_sql
")->fetch_assoc();

// ================= FETCH PAYMENTS =================
$payments = $conn->query("SELECT * FROM payments $where_payments_sql ORDER BY payment_date DESC");
$summary_payments = $conn->query("
    SELECT 
        COUNT(*) AS total_count,
        IFNULL(SUM(amount),0) AS total_amount,
        IFNULL(SUM(CASE WHEN type='Cash' THEN amount END),0) AS cash_total,
        IFNULL(SUM(CASE WHEN type='Card' THEN amount END),0) AS card_total,
        IFNULL(SUM(CASE WHEN type='Transfer' THEN amount END),0) AS transfer_total
    FROM payments
    $where_payments_sql
")->fetch_assoc();
?>

<style>
.report-card{border-radius:12px;}
.table thead th{white-space:nowrap;}
.welcome-msg{background:#f8f9fa;padding:8px 12px;border-radius:8px;margin-bottom:10px;}
@media print{.no-print{display:none!important;}}
</style>

<div class="container-fluid mt-4">

    <button class="btn btn-secondary no-print" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
    
    <div class="welcome-msg no-print">
        <i class="fa fa-user-circle"></i>
        Welcome, <strong><?= htmlspecialchars($username) ?></strong>
    </div>

    <h3 class="mb-2">
        <i class="fa fa-chart-line text-success"></i> Sales & Payments Report
    </h3>

    <hr>

    <!-- ================= FILTERS ================= -->
    <form method="GET" class="row g-2 mb-3 no-print">
        <div class="col-md-2">
            <input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>">
        </div>
        <div class="col-md-2">
            <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>">
        </div>
        <div class="col-md-2">
            <select name="method" class="form-control">
                <option value="">All Methods</option>
                <option <?= $method=='Cash'?'selected':'' ?>>Cash</option>
                <option <?= $method=='Card'?'selected':'' ?>>Card</option>
                <option <?= $method=='Transfer'?'selected':'' ?>>Transfer</option>
            </select>
        </div>
        <div class="col-md-2">
            <select name="outlet" class="form-control">
                <option value="">All Outlets</option>
                <option value="0" <?= $outlet==='0'?'selected':'' ?>>Bar</option>
                <option value="2" <?= $outlet==='2'?'selected':'' ?>>Restaurant</option>
            </select>
        </div>
        <div class="col-md-2">
            <input type="text" name="search" class="form-control" placeholder="Search customer/user" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-2 d-flex gap-1">
            <button class="btn btn-primary w-100"><i class="fa fa-filter"></i> Filter</button>
            <a href="sales_payments.php" class="btn btn-secondary w-100">Reset</a>
        </div>
    </form>

    <!-- ================= ACTION BUTTONS ================= -->
    <div class="mb-3 no-print d-flex gap-2 flex-wrap">
        <button onclick="window.print()" class="btn btn-info"><i class="fa fa-print"></i> Export PDF</button>
        <a href="export_sales_excel.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&method=<?= urlencode($method) ?>&outlet=<?= urlencode($outlet) ?>&search=<?= urlencode($search) ?>" class="btn btn-success"><i class="fa fa-file-excel"></i> Export Excel</a>
        <a href="export_payments_csv.php?from=<?= urlencode($from_date) ?>&to=<?= urlencode($to_date) ?>&type=<?= urlencode($method) ?>&search=<?= urlencode($search) ?>" class="btn btn-success"><i class="fa fa-file-csv"></i> Payments CSV</a>
    </div>

    <!-- ================= SUMMARY CARDS ================= -->
    <div class="row mb-3 text-center">
        <!-- SALES SUMMARY -->
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Total Sales</h6>
                    <h4 class="text-primary"><?= $summary_sales['total_count'] ?? 0 ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Sales Amount (MK)</h6>
                    <h4 class="text-dark"><?= number_format($summary_sales['total_amount'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Cash Sales</h6>
                    <h4 class="text-success"><?= number_format($summary_sales['cash_total'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Card Sales</h6>
                    <h4 class="text-warning"><?= number_format($summary_sales['card_total'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Transfer Sales</h6>
                    <h4 class="text-info"><?= number_format($summary_sales['transfer_total'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>

        <!-- PAYMENTS SUMMARY -->
        <div class="col-md-3 mt-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Total Payments</h6>
                    <h4 class="text-primary"><?= $summary_payments['total_count'] ?? 0 ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-3 mt-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Payments Amount (MK)</h6>
                    <h4 class="text-dark"><?= number_format($summary_payments['total_amount'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2 mt-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Cash Payments</h6>
                    <h4 class="text-success"><?= number_format($summary_payments['cash_total'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2 mt-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Card Payments</h6>
                    <h4 class="text-warning"><?= number_format($summary_payments['card_total'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
        <div class="col-md-2 mt-3">
            <div class="card report-card shadow-sm">
                <div class="card-body">
                    <h6>Transfer Payments</h6>
                    <h4 class="text-info"><?= number_format($summary_payments['transfer_total'] ?? 0,2) ?></h4>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= TABLES ================= -->
    <h5 class="mt-4">Sales Records</h5>
    <div class="table-responsive mb-4">
        <table class="table table-bordered table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th>Date</th>
                    <th>Outlet</th>
                    <th>Payment Method</th>
                    <th>Customer</th>
                    <th>Served By</th>
                    <th>Total</th>
                    <th>VAT</th>
                    <th>Discount</th>
                </tr>
            </thead>
            <tbody>
                <?php if($sales && $sales->num_rows): ?>
                    <?php while($s = $sales->fetch_assoc()): ?>
                        <tr>
                            <td><?= $s['sales_date'] ?></td>
                            <td><?= $s['rest']==2?'Restaurant':'Bar' ?></td>
                            <td><?= $s['payment_method'] ?></td>
                            <td><?= htmlspecialchars($s['customer_id'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($s['created_by'] ?? '-') ?></td>
                            <td><?= number_format($s['total'],2) ?></td>
                            <td><?= number_format($s['vat_total'],2) ?></td>
                            <td><?= number_format($s['discount'],2) ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="8" class="text-center text-danger">No sales found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <h5>Payments Records</h5>
    <div class="table-responsive mb-4">
        <table class="table table-bordered table-striped table-sm">
            <thead class="table-dark">
                <tr>
                    <th>Date</th>
                    <th>Reference</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Received By</th>
                </tr>
            </thead>
            <tbody>
                <?php if($payments && $payments->num_rows): ?>
                    <?php while($p = $payments->fetch_assoc()): ?>
                        <tr>
                            <td><?= $p['payment_date'] ?></td>
                            <td><?= htmlspecialchars($p['reference'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($p['type']) ?></td>
                            <td><?= number_format($p['amount'],2) ?></td>
                            <td><?= htmlspecialchars($p['received_by'] ?? '-') ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="5" class="text-center text-danger">No payments found</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>

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