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

$user_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 0;
$user_role = strtolower($_SESSION['role'] ?? 'guest');
$today = date('Y-m-d');

// ================= FILTERS =================
$from = $_GET['from'] ?? $today;
$to   = $_GET['to'] ?? $today;
$payment_method = $_GET['payment_method'] ?? '';
$search = $_GET['search'] ?? '';
$created_by = $_GET['created_by'] ?? '';

$where = "DATE(s.sale_date) BETWEEN '$from' AND '$to'";

if(!empty($payment_method)){
    $where .= " AND s.payment_method='$payment_method'";
}

if(!empty($search)){
    $search_safe = $conn->real_escape_string($search);
    $where .= " AND (
        s.id LIKE '%$search_safe%' OR
        c.name LIKE '%$search_safe%'
    )";
}

// Filter by created_by only if admin
if(!empty($created_by) && $user_role=='admin'){
    $created_by_safe = $conn->real_escape_string($created_by);
    $where .= " AND s.created_by='$created_by_safe'";
}

// ================= FETCH SALES =================
$sales = $conn->query("
    SELECT s.*, c.name AS customer_name
    FROM sales s
    LEFT JOIN customers c ON s.customer_id=c.id
    WHERE $where AND s.rest = 0
    ORDER BY s.id DESC
");

// ================= FILTERED TOTAL =================
$filtered_total = $conn->query("
    SELECT IFNULL(SUM(s.total),0) AS total
    FROM sales s
    LEFT JOIN customers c ON s.customer_id=c.id
    WHERE $where AND s.rest = 0
")->fetch_assoc()['total'];


// ================= FILTERED DISCOUNT =================
$filtered_discount = $conn->query("
    SELECT IFNULL(SUM(s.discount),0) AS total_discount
    FROM sales s
    LEFT JOIN customers c ON s.customer_id=c.id
    WHERE $where AND s.rest = 0
")->fetch_assoc()['total_discount'];

// ================= TODAY TOTAL =================
$today_total = $conn->query("
    SELECT IFNULL(SUM(total),0) AS total
    FROM sales
    WHERE DATE(sale_date)=CURDATE() AND rest = 0
")->fetch_assoc()['total'];

$today_discount = $conn->query("
    SELECT IFNULL(SUM(discount),0) AS total_discount
    FROM sales
    WHERE DATE(sale_date)=CURDATE() AND rest = 0
")->fetch_assoc()['total_discount'];
// ================= PAYMENT RECON =================
$recon = $conn->query("
    SELECT payment_method, SUM(total) AS amount
    FROM sales
    WHERE DATE(sale_date)='$today' AND rest = 0
    GROUP BY payment_method
");

$net_total = $filtered_total - $filtered_discount;

// ================= GET ALL CASHIERS/ADMINS =================
$cashiers = [];
if($user_role=='admin'){
    $res = $conn->query("SELECT DISTINCT created_by FROM sales ORDER BY created_by ASC");
    while($row = $res->fetch_assoc()){
        $cashiers[] = $row['created_by'];
    }
}
?>

<style>
@media print {
    body * { visibility: hidden; }
    #printArea, #printArea * { visibility: visible; }
    #printArea { position:absolute; left:0; top:0; width:100%; }
    .no-print { display:none !important; }
}
</style>

<div class="container mt-4">

<div class="welcome-msg no-print">
<i class="fa fa-user-circle"></i>
Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
</div>

<!-- ================= TOP BUTTONS ================= -->
<div class="mb-3 no-print">

<button class="btn btn-secondary" onclick="history.back()">
<i class="fa fa-arrow-left"></i> Back
</button>

<button onclick="printSales()" class="btn btn-danger">
🖨️ Print Filtered
</button>

<a href="sales_pos.php" class="btn btn-primary">Bar POS</a>

 <!-- Export to Excel -->
    <!-- Export Filtered -->
    <a href="export_bar_sales_excel.php?from=<?= $from ?>&to=<?= $to ?>&payment_method=<?= urlencode($payment_method) ?>&search=<?= urlencode($search) ?>&created_by=<?= urlencode($created_by) ?>" 
       class="btn btn-success">
       📥 Export Filtered
    </a>

    <!-- Export All -->
    <a href="export_bar_sales_excel.php?all=1" class="btn btn-warning">
       📥 Export All Sales
    </a>
</div>

<h3 class="text-center">📊 Bar Sales Dashboard</h3>
<hr>

<!-- ================= FILTER FORM ================= -->
<form method="GET" class="row g-2 mb-3 no-print">

<div class="col-md-2">
<label>From</label>
<input type="date" name="from" value="<?= $from ?>" class="form-control">
</div>

<div class="col-md-2">
<label>To</label>
<input type="date" name="to" value="<?= $to ?>" class="form-control">
</div>

<div class="col-md-2">
<label>Payment</label>
<select name="payment_method" class="form-control">
<option value="">All</option>
<option <?= $payment_method=='Cash'?'selected':'' ?>>Cash</option>
<option <?= $payment_method=='Mobile Money'?'selected':'' ?>>Mobile Money</option>
<option <?= $payment_method=='Card'?'selected':'' ?>>Card</option>
<option <?= $payment_method=='Bank Transfer'?'selected':'' ?>>Bank Transfer</option>
</select>
</div>

<div class="col-md-3">
<label>Search</label>
<input type="text" name="search" value="<?= $search ?>"
placeholder="Sale ID or customer"
class="form-control">
</div>

<?php if($user_role=='admin'): ?>
<div class="col-md-2">
<label>Filter By Sales Personel</label>
<select name="created_by" class="form-control">
    <option value="">All</option>
    <?php foreach($cashiers as $c): ?>
        <option value="<?= $c ?>" <?= $c==$created_by?'selected':'' ?>>
            <?= $c ?>
        </option>
    <?php endforeach; ?>
</select>
</div>
<?php endif; ?>

<div class="col-md-1 mt-4">
<button class="btn btn-primary w-100">🔍 Apply Filters</button>
</div>

</form>

<!-- ================= TODAY SUMMARY ================= -->
<div class="alert alert-success">
<strong>Today's Sales:</strong>
MK <?= number_format($today_total,2) ?>
|
<strong>Today's Discounts:</strong>
MK <?= number_format($today_discount,2) ?>
</div>

<!-- ================= PRINT AREA ================= -->
<div id="printArea">

<div class="text-center mb-2">
<h4>Bar Sales Report</h4>
<small>
Period: <?= $from ?> → <?= $to ?>
<?php if($payment_method): ?>
| Payment: <?= $payment_method ?>
<?php endif; ?>
<?php if($user_role=='admin' && $created_by): ?>
| Cashier: <?= $created_by ?>
<?php endif; ?>
</small>
</div>

<div class="row mb-3">

<div class="col-md-4">
<div class="alert alert-info">
<strong>Gross Sales:</strong><br>
MK <?= number_format($filtered_total,2) ?>
</div>
</div>

<div class="col-md-4">
<div class="alert alert-warning">
<strong>Total Discounts:</strong><br>
MK <?= number_format($filtered_discount,2) ?>
</div>
</div>

<div class="col-md-4">
<div class="alert alert-success">
<strong>Net Sales:</strong><br>
MK <?= number_format($net_total,2) ?>
</div>
</div>

</div>

<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
<th>#</th>
<th>Date</th>
<th>Customer</th>
<th>Payment</th>
<th>Total (MK)</th>
<th>Discount (MK)</th>
<?php if($user_role=='admin'): ?>
<th>Created By</th>
<?php endif; ?>
<th class="no-print">Action</th>
</tr>
</thead>
<tbody>
<?php $i=1; while($row=$sales->fetch_assoc()): ?>
<tr>
<td><?= $i++ ?></td>
<td><?= $row['sale_date'] ?></td>
<td><?= $row['customer_name'] ?? 'Walk-in' ?></td>
<td><?= $row['payment_method'] ?></td>
<td><strong><?= number_format($row['total'],2) ?></strong></td>
<td><strong><?= number_format($row['discount'],2) ?></strong></td>
<?php if($user_role=='admin'): ?>
<td><?= $row['created_by'] ?></td>
<?php endif; ?>
<td class="no-print">
<a href="print_bar_receipt.php?id=<?= $row['id'] ?>"
class="btn btn-sm btn-success" target="_blank">🧾Print Receipt</a>


</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>
</div>

<script>
function printSales(){
    window.print();
}
</script>

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