<?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">

    <!-- Page Title -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold">Expenses</h4>
        <a href="/beauty_pos/expenses/add.php" class="btn btn-primary">
            <i class="fa fa-plus"></i> Add Expense
        </a>
    </div>

    <?php
    // Total Expenses
    $totalQuery = mysqli_query($conn, "SELECT SUM(amount) as total FROM expenses");
    $totalData = mysqli_fetch_assoc($totalQuery);
    $total = $totalData['total'] ?? 0;

    // Category Breakdown
    $breakdownQuery = mysqli_query($conn, "
        SELECT category, SUM(amount) as total 
        FROM expenses 
        GROUP BY category
        ORDER BY total DESC
    ");

    $categories = [];
    $amounts = [];

    while($row = mysqli_fetch_assoc($breakdownQuery)){
        $categories[] = $row['category'];
        $amounts[] = $row['total'];
    }
    ?>

    <div class="row g-4">

        <!-- Chart -->
        <div class="col-xl-8 col-lg-7 col-12">
            <div class="card rounded-4 shadow border-0 p-3">
                <canvas id="expenseChart"></canvas>
            </div>
        </div>

        <!-- Breakdown -->
        <div class="col-xl-4 col-lg-5 col-12">
            <div class="card rounded-4 shadow border-0 p-3">
                <h6 class="fw-bold mb-3">Expense Breakdown</h6>

                <?php
                mysqli_data_seek($breakdownQuery, 0);
                while($row = mysqli_fetch_assoc($breakdownQuery)){
                ?>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span><?php echo htmlspecialchars($row['category']); ?></span>
                        <span class="fw-semibold">₹<?php echo number_format($row['total'],2); ?></span>
                    </div>
                <?php } ?>

                <hr>
                <div class="d-flex justify-content-between">
                    <strong>Total</strong>
                    <strong class="text-primary">₹<?php echo number_format($total,2); ?></strong>
                </div>
            </div>
        </div>

    </div>

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

            <!-- Search -->
            <form method="GET" class="row g-3 mb-3">
                <div class="col-md-4 col-12">
                    <input type="text" name="search" class="form-control" placeholder="Search expense..." value="<?php echo $_GET['search'] ?? ''; ?>">
                </div>
                <div class="col-md-2 col-6">
                    <button class="btn btn-dark w-100">Search</button>
                </div>
            </form>

            <?php
            $limit = 10;
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $offset = ($page - 1) * $limit;

            $search = $_GET['search'] ?? '';
            $where = "";

            if(!empty($search)){
                $where = "WHERE expense_name LIKE '%$search%' OR category LIKE '%$search%'";
            }

            $query = mysqli_query($conn, "SELECT * FROM expenses $where ORDER BY id DESC LIMIT $limit OFFSET $offset");

            $countQuery = mysqli_query($conn, "SELECT COUNT(*) as total FROM expenses $where");
            $countData = mysqli_fetch_assoc($countQuery);
            $totalRows = $countData['total'];
            $totalPages = ceil($totalRows / $limit);
            ?>

            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Amount</th>
                            <th>Date</th>
                            <th>Notes</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if(mysqli_num_rows($query) > 0){
                            $i = $offset + 1;
                            while($row = mysqli_fetch_assoc($query)){
                        ?>
                        <tr>
                            <td><?php echo $i++; ?></td>
                            <td><?php echo htmlspecialchars($row['expense_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['category']); ?></td>
                            <td>₹<?php echo number_format($row['amount'],2); ?></td>
                            <td><?php echo date("d M Y", strtotime($row['expense_date'])); ?></td>
                            <td><?php echo htmlspecialchars($row['notes']); ?></td>
                            <td class="text-end">
                                <a href="/beauty_pos/expenses/edit.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning">
                                    <i class="fa fa-edit"></i>
                                </a>
                                <a href="/beauty_pos/expenses/delete.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this expense?')">
                                    <i class="fa fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php } } else { ?>
                        <tr>
                            <td colspan="7" class="text-center">No expenses found</td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <nav>
                <ul class="pagination justify-content-end">
                    <?php for($i=1; $i<=$totalPages; $i++){ ?>
                        <li class="page-item <?php if($i==$page) echo 'active'; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php } ?>
                </ul>
            </nav>

        </div>
    </div>

</div>

<?php include_once "../includes/footer.php"; ?>
</div>

<script>
const ctx = document.getElementById('expenseChart');

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