<?php
session_start();
include "header.php";
include "db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// Default to current month
$month = isset($_POST['month']) ? $_POST['month'] : date('Y-m');

// Search filter
$search = isset($_POST['search']) ? trim($_POST['search']) : "";

// Build query
$sql = "SELECT sale_id, sale_date, customer_name, item_name, description, amount_payable, amount_paid, 
        (amount_payable - amount_paid) AS balance
        FROM sales
        WHERE staff_id = ?
        AND DATE_FORMAT(sale_date, '%Y-%m') = ?";

if (!empty($search)) {
    $sql .= " AND (customer_name LIKE ? OR item_name LIKE ? OR description LIKE ?)";
}

$sql .= " ORDER BY sale_date ASC";

$stmt = $conn->prepare($sql);

if (!empty($search)) {
    $search_param = "%" . $search . "%";
    $stmt->bind_param("issss", $user_id, $month, $search_param, $search_param, $search_param);
} else {
    $stmt->bind_param("is", $user_id, $month);
}

$stmt->execute();
$result = $stmt->get_result();

$total_payable = $total_paid = $total_balance = 0;
?>

<div class="container py-4">
   <div>
        <h2 class="text-primary ">Monthly Report (<?= htmlspecialchars($month) ?>)</h2>
        <a href="dashboard.php" class="btn btn-secondary mb-3">Back to Dashboard</a>
 </div>

    <!-- Filter Form -->
    <form method="post" class="mb-3 row g-2">
        <div class="col-md-3 col-12">
           
            <input type="month" name="month" value="<?= htmlspecialchars($month) ?>" required class="form-control">
        </div>
      
		
		<div class="col-md-3 col-12 ">
                <input type="search" name="search" class="form-control" 
       placeholder="Search customer, item, or description" 
       value="<?php echo htmlspecialchars($search); ?>">

            </div>
		<div class="col-md-3 col-12">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
    </form>

<!--Export button-->
<form method="POST" action="user_export_sale.php" class="mb-3">
    <input type="hidden" name="report_type" value="monthly">
    <input type="hidden" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
    <input type="hidden" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
    <input type="hidden" name="search" value="<?= htmlspecialchars($search ?? '') ?>">
    <button type="submit" class="btn btn-success btn-sm">Export CSV</button>
</form>


    <div class="table-responsive bg-white shadow-sm rounded p-3">
        <table class="table table-bordered table-hover align-middle">
            <thead class="table-dark">
                <tr>
                    <th>Date</th>
                    <th>Customer</th>
                    <th>Item</th>
                    <th>Description</th>
                    <th class="text-end">Amount Payable</th>
                    <th class="text-end">Amount Paid</th>
                    <th class="text-end">Balance</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()):
                        $total_payable += $row['amount_payable'];
                        $total_paid += $row['amount_paid'];
                        $total_balance += $row['balance'];
                    ?>
                    <tr>
                        <td><?= htmlspecialchars(date("d M Y", strtotime($row['sale_date']))) ?></td>
                        <td><?= htmlspecialchars($row['customer_name'] ?: '-') ?></td>
                        <td><?= htmlspecialchars($row['item_name']) ?></td>
                        <td><?= htmlspecialchars($row['description'] ?: '-') ?></td>
                        <td class="text-end"><?= number_format($row['amount_payable'], 2) ?></td>
                        <td class="text-end"><?= number_format($row['amount_paid'], 2) ?></td>
                        <td class="text-end"><?= number_format($row['balance'], 2) ?></td>
                    </tr>
                    <?php endwhile; ?>
                    <tr class="fw-bold table-secondary">
                        <td colspan="4" class="text-end">TOTAL</td>
                        <td class="text-end"><?= number_format($total_payable, 2) ?></td>
                        <td class="text-end"><?= number_format($total_paid, 2) ?></td>
                        <td class="text-end"><?= number_format($total_balance, 2) ?></td>
                    </tr>
                <?php else: ?>
                    <tr><td colspan="7" class="text-center text-danger">No sales found for this month.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include "footer.php"; ?>
