<?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'] ?? ''; // 0=Bar, 2=Restaurant
$search    = $_GET['search'] ?? '';

// ================= WHERE BUILDER =================
$where = [];

if($from_date){
    $where[] = "DATE(sales_date) >= '".$conn->real_escape_string($from_date)."'";
}

if($to_date){
    $where[] = "DATE(sales_date) <= '".$conn->real_escape_string($to_date)."'";
}

if($method){
    $where[] = "payment_method = '".$conn->real_escape_string($method)."'";
}

if($outlet !== ''){
    $where[] = "rest = '".$conn->real_escape_string($outlet)."'";
}

if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(customer_id LIKE '%$s%' OR created_by LIKE '%$s%')";
}

$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH SALES =================
$sales = $conn->query("
    SELECT *
    FROM sales
    $where_sql
    ORDER BY sales_date DESC
");

// ================= SUMMARY =================
$summary = $conn->query("
    SELECT 
        COUNT(*) AS total_sales,
        IFNULL(SUM(total),0) AS total_amount,
        IFNULL(SUM(vat_total),0) AS vat_total,
        IFNULL(SUM(discount),0) AS discount_total,
        IFNULL(SUM(CASE WHEN rest=0 THEN total END),0) AS bar_total,
        IFNULL(SUM(CASE WHEN rest=2 THEN total END),0) AS restaurant_total
    FROM sales
    $where_sql
")->fetch_assoc();

$total_sales       = $summary['total_sales'] ?? 0;
$total_amount      = $summary['total_amount'] ?? 0;
$vat_total         = $summary['vat_total'] ?? 0;
$discount_total    = $summary['discount_total'] ?? 0;
$bar_total         = $summary['bar_total'] ?? 0;
$restaurant_total  = $summary['restaurant_total'] ?? 0;
?>

<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 Report
</h3>

<?php if($from_date == $to_date): ?>
<div class="alert alert-info py-2">
    Showing sales for <strong><?= date('d M Y', strtotime($from_date)) ?></strong>
</div>
<?php endif; ?>

<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="Customer / User"
               value="<?= htmlspecialchars($search) ?>">
    </div>

    <div class="col-md-1">
        <button class="btn btn-primary w-100">
            <i class="fa fa-filter"></i>
        </button>
    </div>

    <div class="col-md-1">
        <a href="sales_report.php" class="btn btn-secondary w-100">Reset</a>
    </div>
</form>

<!-- ================= EXPORT ================= -->
<div class="mb-3 no-print d-flex gap-2 flex-wrap">

    <button onclick="window.print()" class="btn btn-danger">
        <i class="fa fa-file-pdf"></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>

</div>

<!-- ================= SUMMARY ================= -->
<div class="row mb-3 text-center">

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Transactions</h6>
                <h4 class="text-primary"><?= $total_sales ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Total Sales</h6>
                <h4><?= number_format($total_amount,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>VAT</h6>
                <h4 class="text-info"><?= number_format($vat_total,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Discount</h6>
                <h4 class="text-warning"><?= number_format($discount_total,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Bar</h6>
                <h4 class="text-success"><?= number_format($bar_total,2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card report-card shadow-sm">
            <div class="card-body">
                <h6>Restaurant</h6>
                <h4 class="text-dark"><?= number_format($restaurant_total,2) ?></h4>
            </div>
        </div>
    </div>

</div>

<!-- ================= TABLE ================= -->
<div class="table-responsive">
<table class="table table-bordered table-striped table-sm">
<thead class="table-dark">
<tr>
    <th>Date</th>
    <th>Outlet</th>
    <th>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><?= htmlspecialchars($s['sales_date']) ?></td>
    <td>
        <span class="badge bg-<?= $s['rest']==2?'dark':'success' ?>">
            <?= $s['rest']==2 ? 'Restaurant' : 'Bar' ?>
        </span>
    </td>
    <td><?= htmlspecialchars($s['payment_method']) ?></td>
    <td><?= htmlspecialchars($s['customer_id'] ?? '-') ?></td>
    <td><?= htmlspecialchars($s['created_by'] ?? '-') ?></td>
    <td class="fw-bold"><?= 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>

<tfoot class="table-dark">
<tr>
    <th colspan="5">TOTAL</th>
    <th><?= number_format($total_amount,2) ?></th>
    <th><?= number_format($vat_total,2) ?></th>
    <th><?= number_format($discount_total,2) ?></th>
</tr>
</tfoot>
</table>
</div>

</div>

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