<?php
session_start();
if(!isset($_SESSION['user_id'])){
    header("Location: /beauty_pos/login.php");
    exit();
}
include_once "../config/database.php";
?>

<?php include_once "../includes/header.php"; ?>
<?php include_once "../includes/sidebar.php"; ?>

<div class="overlay" id="overlay"></div>

<div class="main-content">
<?php include_once "../includes/topbar.php"; ?>

<div class="container-fluid py-4">

    <h4 class="fw-bold mb-4">Reports</h4>

    <?php
    // Revenue (from sales)
    $revQuery = mysqli_query($conn, "SELECT SUM(total) as revenue FROM sales");
    $revData = mysqli_fetch_assoc($revQuery);
    $revenue = $revData['revenue'] ?? 0;

    // Expenses
    $expQuery = mysqli_query($conn, "SELECT SUM(amount) as expenses FROM expenses");
    $expData = mysqli_fetch_assoc($expQuery);
    $expenses = $expData['expenses'] ?? 0;

    $profit = $revenue - $expenses;

    // Payment Methods
    $payQuery = mysqli_query($conn, "
        SELECT payment_method, COUNT(*) as total 
        FROM sales 
        GROUP BY payment_method
    ");

    $methods = [];
    $counts = [];

    while($row = mysqli_fetch_assoc($payQuery)){
        $methods[] = $row['payment_method'];
        $counts[] = $row['total'];
    }
    ?>

    <div class="row g-4">

        <!-- Revenue vs Expenses -->
        <div class="col-xl-6 col-lg-6 col-12">
            <div class="card rounded-4 shadow border-0 p-3">
                <h6 class="fw-bold mb-3">Revenue vs Expenses</h6>
                <canvas id="barChart"></canvas>
            </div>
        </div>

        <!-- Payment Methods -->
        <div class="col-xl-6 col-lg-6 col-12">
            <div class="card rounded-4 shadow border-0 p-3">
                <h6 class="fw-bold mb-3">Payment Methods</h6>
                <canvas id="pieChart"></canvas>
            </div>
        </div>

    </div>
        <!-- Summary Cards -->
    <div class="row g-4 mt-2">

        <div class="col-xl-4 col-md-6 col-12">
            <div class="card rounded-4 shadow border-0 p-3 text-center">
                <h6>Total Revenue</h6>
                <h4 class="text-success">₹<?php echo number_format($revenue,2); ?></h4>
            </div>
        </div>

        <div class="col-xl-4 col-md-6 col-12">
            <div class="card rounded-4 shadow border-0 p-3 text-center">
                <h6>Total Expenses</h6>
                <h4 class="text-danger">₹<?php echo number_format($expenses,2); ?></h4>
            </div>
        </div>

        <div class="col-xl-4 col-md-6 col-12">
            <div class="card rounded-4 shadow border-0 p-3 text-center">
                <h6>Net Profit</h6>
                <h4 class="<?php echo $profit >=0 ? 'text-success':'text-danger'; ?>">
                    ₹<?php echo number_format($profit,2); ?>
                </h4>
            </div>
        </div>

    </div>
    <!-- Sales Report Table -->
<div class="card rounded-4 shadow border-0 mt-4">
    <div class="card-body">

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold mb-0">Sales Report</h6>
        </div>

        <?php
        $salesQuery = mysqli_query($conn, "
            SELECT sales.*, customers.customer_name 
            FROM sales 
            LEFT JOIN customers ON sales.customer_id = customers.id
            ORDER BY sales.id DESC
            LIMIT 10
        ");
        ?>

        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th>Order</th>
                        <th>Date</th>
                        <th>Customer</th>
                        <th>Items</th>
                        <th>Total</th>
                        <th>Payment</th>
                    </tr>
                </thead>
                <tbody>

                <?php
                if(mysqli_num_rows($salesQuery) > 0){
                    while($row = mysqli_fetch_assoc($salesQuery)){

                        // Count items
                        $sale_id = $row['id'];
                        $itemQ = mysqli_query($conn, "SELECT SUM(quantity) as items FROM sale_items WHERE sale_id='$sale_id'");
                        $itemData = mysqli_fetch_assoc($itemQ);
                        $items = $itemData['items'] ?? 0;
                ?>

                    <tr>
                        <td>#<?php echo $row['invoice_no']; ?></td>
                        <td><?php echo date("Y-m-d", strtotime($row['created_at'])); ?></td>

                        <td>
                        <?php 
                        echo !empty($row['customer_name']) 
                        ? htmlspecialchars($row['customer_name']) 
                        : 'Walk-in'; 
                        ?>
                        </td>

                        <td><?php echo $items; ?> items</td>

                        <td class="fw-semibold">
                            ₹<?php echo number_format($row['total'],2); ?>
                        </td>

                        <td><?php echo $row['payment_method']; ?></td>
                    </tr>

                <?php }} else { ?>
                    <tr>
                        <td colspan="6" class="text-center">No sales found</td>
                    </tr>
                <?php } ?>

                </tbody>
            </table>
        </div>

    </div>
</div>

</div>

<?php include_once "../includes/footer.php"; ?>
</div>
<script>
const barCtx = document.getElementById('barChart');

new Chart(barCtx, {
    type: 'bar',
    data: {
        labels: ['Revenue','Expenses','Profit'],
        datasets: [{
            label: 'Amount',
            data: [
                <?php echo $revenue; ?>,
                <?php echo $expenses; ?>,
                <?php echo $profit; ?>
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display:false }
        }
    }
});

const pieCtx = document.getElementById('pieChart');

new Chart(pieCtx, {
    type: 'doughnut',
    data: {
        labels: <?php echo json_encode($methods); ?>,
        datasets: [{
            data: <?php echo json_encode($counts); ?>,
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                position:'bottom'
            }
        }
    }
});
</script>