<?php
// ===================== ERROR TRACKING =====================
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

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

// ===================== USER INFO =====================
$current_user = $_SESSION['username'] ?? '';
$current_role = strtolower($_SESSION['role'] ?? 'guest');

// ===================== DEFAULTS =====================
$today = date('Y-m-d');
$from = $_GET['from'] ?? $today;
$to = $_GET['to'] ?? $today;
$payment_method = $_GET['payment_method'] ?? '';
$search = $_GET['search'] ?? '';

// ===================== BUILD WHERE =====================
$where = "DATE(s.sale_date) BETWEEN ? AND ? AND s.store_id = 3";
$params = [$from, $to];
$types = "ss";

// 🔐 ROLE FILTER (NON-ADMIN)
if ($current_role !== 'admin') {
    $where .= " AND s.created_by = ?";
    $params[] = $current_user;
    $types .= "s";
}

// Payment filter
if (!empty($payment_method)) {
    $where .= " AND s.payment_method = ?";
    $params[] = $payment_method;
    $types .= "s";
}

// Search filter
if (!empty($search)) {
    $where .= " AND (s.id LIKE ? OR s.bill_no LIKE ?)";
    $searchLike = "%$search%";
    $params[] = $searchLike;
    $params[] = $searchLike;
    $types .= "ss";
}

// ===================== FETCH SALES =====================
try {

    $stmt = $conn->prepare("
        SELECT s.*, c.name AS customer_name
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        WHERE $where
        ORDER BY s.id DESC
    ");

    if (!$stmt) {
        throw new Exception($conn->error);
    }

    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $sales = $stmt->get_result();

} catch (Exception $e) {
    die("<div class='alert alert-danger'>Error: " . htmlspecialchars($e->getMessage()) . "</div>");
}

// ===================== FILTERED TOTAL =====================
$stmt_sum = $conn->prepare("
    SELECT IFNULL(SUM(total),0) AS total
    FROM sales s
    WHERE $where
");

$stmt_sum->bind_param($types, ...$params);
$stmt_sum->execute();
$filtered_total = $stmt_sum->get_result()->fetch_assoc()['total'] ?? 0;

// ===================== TODAY TOTAL =====================
if ($current_role === 'admin') {
    $stmt_today = $conn->prepare("
        SELECT IFNULL(SUM(total),0) AS total
        FROM sales
        WHERE DATE(sale_date)=CURDATE() AND store_id=3
    ");
    $stmt_today->execute();
} else {
    $stmt_today = $conn->prepare("
        SELECT IFNULL(SUM(total),0) AS total
        FROM sales
        WHERE DATE(sale_date)=CURDATE()
        AND store_id=3
        AND created_by = ?
    ");
    $stmt_today->bind_param("s", $current_user);
    $stmt_today->execute();
}

$today_total = $stmt_today->get_result()->fetch_assoc()['total'] ?? 0;
?>

<style>
@media print {
    body * { visibility: hidden; }
    #printArea, #printArea * { visibility: visible; }
    #printArea { position:absolute; left:0; top:0; width:100%; }
}
</style>

<div class="container mt-4">

<div class="welcome-msg">
<i class="fa fa-user-circle"></i>
Welcome, <strong><?= htmlspecialchars($current_user ?: 'Guest') ?></strong>!
</div>

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

<a href="restaurant_pos.php" class="btn btn-primary">Restaurant POS</a>
<a href="restaurant_orders_list.php" class="btn btn-info">Restaurant Orders</a>

<h3 class="text-center mt-3">🍽️ Restaurant Sales</h3>
<hr>

<!-- ================= SUMMARY ================= -->

<div class="row mb-3">
<div class="col-md-6">
<div class="alert alert-success">
<strong>Today's Sales:</strong> MK <?= number_format($today_total,2) ?>
</div>
</div>

<div class="col-md-6">
<div class="alert alert-primary">
<strong>Filtered Total:</strong> MK <?= number_format($filtered_total,2) ?>
</div>
</div>
</div>

<!-- ================= QUICK FILTERS ================= -->

<div class="mb-2">
<a href="?from=<?= $today ?>&to=<?= $today ?>" class="btn btn-sm btn-outline-primary">Today</a>
<a href="?from=<?= date('Y-m-d', strtotime('-1 day')) ?>&to=<?= date('Y-m-d', strtotime('-1 day')) ?>" class="btn btn-sm btn-outline-secondary">Yesterday</a>
<a href="?from=<?= date('Y-m-01') ?>&to=<?= date('Y-m-d') ?>" class="btn btn-sm btn-outline-success">This Month</a>
</div>

<!-- ================= FILTER FORM ================= -->

<form method="GET" class="row g-3 mb-3">

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

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

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

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

<div class="col-md-2 mt-4">
<button class="btn btn-primary w-100">
<i class="fa fa-filter"></i> Filter
</button>
</div>

</form>

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

<!-- ================= PRINT AREA ================= -->

<div id="printArea">

<table class="table table-bordered table-striped" style="font-size:12px;">

<thead class="bg-dark text-white">
<tr>
<th>#</th>
<th>Sale ID</th>
<th>Bill No</th>
<th>Date</th>
<th>Customer</th>
<th>Payment</th>
<th>Total (MK)</th>
<th>Prints</th>
<th width="220">Action</th>
</tr>
</thead>

<tbody>

<?php 
$i = 1;
if($sales && $sales->num_rows > 0):
while($row = $sales->fetch_assoc()):

$rowClass = ($row['print_count'] >= 2) ? 'table-warning' : '';
?>

<tr class="<?= $rowClass ?>">

<td><?= $i++ ?></td>
<td><strong>#<?= $row['id'] ?></strong></td>
<td><?= htmlspecialchars($row['bill_no'] ?? '-') ?></td>
<td><?= htmlspecialchars($row['sale_date']) ?></td>
<td><?= htmlspecialchars($row['customer_name'] ?? 'Walk-in') ?></td>
<td><?= htmlspecialchars($row['payment_method']) ?></td>
<td><strong><?= number_format($row['total'],2) ?></strong></td>
<td><span class="badge bg-info"><?= intval($row['print_count']) ?></span></td>

<td>


<?php if($row['print_count'] < 2): ?>
<a href="print_restaurant_receipt.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-success" target="_blank">🧾 Print</a>
<?php else: ?>
<button class="btn btn-sm btn-secondary" disabled>Printed Twice</button>
<?php endif; ?>
</td>

</tr>

<?php endwhile; else: ?>
<tr>
<td colspan="9" class="text-center">No sales found for the selected filter.</td>
</tr>
<?php endif; ?>

</tbody>
</table>

</div>
</div>

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

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