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

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

// Default to current month
$month = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
$office_filter = isset($_GET['office_name']) ? $_GET['office_name'] : "";
$search = isset($_GET['search']) ? trim($_GET['search']) : "";

// Get offices
$offices = mysqli_query($conn, "SELECT DISTINCT office_name FROM sales ORDER BY office_name ASC");

// Query
$query = "SELECT * FROM sales WHERE DATE_FORMAT(sale_date, '%Y-%m') = '$month'";
if (!empty($office_filter)) {
    $query .= " AND office_name = '$office_filter'";
}
if (!empty($search)) {
    $query .= " AND (customer_name LIKE '%$search%' OR item_name LIKE '%$search%')";
}
$query .= " ORDER BY sale_date DESC";
$result = mysqli_query($conn, $query);

// Totals
$total_payable = $total_paid = $total_balance = 0;

// Chart data arrays
$labels = [];
$payable_data = [];
$paid_data = [];
$balance_data = [];
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin - Monthly Sales Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="container mt-4">
<h2 class="mb-3">Admin - Monthly Sales Report</h2>
<a href="admin_dashboard.php" class="btn btn-secondary btn-sm" >Back to Dashboard</a>
<br>
<br>
<!-- Filter Form -->
<form method="GET" class="mb-3 row g-2 align-items-center">
    <div class="col-md-3 col-12">
        <select name="office_name" class="form-select">
            <option value="">-- All Offices --</option>
            <?php while ($row = mysqli_fetch_assoc($offices)): ?>
                <option value="<?php echo $row['office_name']; ?>" <?php if ($office_filter == $row['office_name']) echo "selected"; ?>>
                    <?php echo $row['office_name']; ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
	
	<div class="col-md-3 col-12">
        <input type="month" name="month" class="form-control" value="<?php echo $month; ?>">
    </div>
    
    <div class="col-md-3 col-12">
        <input type="search" name="search" class="form-control" placeholder="Search by Customer/Item" 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="export_sales.php" class="mb-3">
    <input type="hidden" name="report_type" value="monthly">
    <input type="hidden" name="month" value="<?php echo $month; ?>">
    <input type="hidden" name="office_name" value="<?php echo $office_filter; ?>">
    <input type="hidden" name="search" value="<?php echo $search; ?>">
    <button type="submit" class="btn btn-success">Export CSV</button>
</form>

<!-- Table -->
<div class="table-responsive">
<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>Date</th>
            <th>Customer</th>
            <th>Item</th>
            <th>Description</th>
            <th>Amount Payable</th>
            <th>Amount Paid</th>
            <th>Balance</th>
        </tr>
    </thead>
    <tbody>
        <?php if (mysqli_num_rows($result) > 0): ?>
            <?php while ($row = mysqli_fetch_assoc($result)): 
                // Totals
                $total_payable += $row['amount_payable'];
                $total_paid += $row['amount_paid'];
                $total_balance += $row['balance'];

                // Chart data
                $labels[] = date("d M", strtotime($row['sale_date']));
                $payable_data[] = $row['amount_payable'];
                $paid_data[] = $row['amount_paid'];
                $balance_data[] = $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><?= number_format($row['amount_payable'], 2) ?></td>
                    <td><?= number_format($row['amount_paid'], 2) ?></td>
                    <td><?= number_format($row['balance'], 2) ?></td>
                </tr>
            <?php endwhile; ?>
            <tr class="fw-bold table-secondary">
                <td colspan="4" class="text-end">TOTAL</td>
                <td><?= number_format($total_payable, 2) ?></td>
                <td><?= number_format($total_paid, 2) ?></td>
                <td><?= number_format($total_balance, 2) ?></td>
            </tr>
        <?php else: ?>
            <tr><td colspan="7" class="text-center">No sales found for this month.</td></tr>
        <?php endif; ?>
    </tbody>
</table>
</div>

<!-- Chart -->
<div class="mt-5">
    <h4>Monthly Sales Chart</h4>
    <canvas id="salesChart"></canvas>
</div>

<script>
const ctx = document.getElementById('salesChart').getContext('2d');
const salesChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode($labels); ?>,
        datasets: [
            {
                label: 'Amount Payable',
                data: <?php echo json_encode($payable_data); ?>,
                borderColor: 'rgba(255, 99, 132, 1)',
                fill: false
            },
            {
                label: 'Amount Paid',
                data: <?php echo json_encode($paid_data); ?>,
                borderColor: 'rgba(54, 162, 235, 1)',
                fill: false
            },
            {
                label: 'Balance',
                data: <?php echo json_encode($balance_data); ?>,
                borderColor: 'rgba(255, 206, 86, 1)',
                fill: false
            }
        ]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'top' }
        },
        scales: {
            y: { beginAtZero: true }
        }
    }
});
</script>

<?php include "footer.php"; ?>
</body>
</html>
