<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

// Check permissions
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'FINANCE_MANAGER'])) {
    header('Location: access_denied.php');
    exit();
}

$fiscal_year = $_GET['year'] ?? date('Y');
$fiscal_period = $_GET['period'] ?? date('n');

// Execute Stored Procedure
$sql = "CALL GenerateTrialBalance(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $fiscal_year, $fiscal_period);
$stmt->execute();
$result = $stmt->get_result();

// Consume first result set (Trial Balance lines)
$tb_lines = [];
while ($row = $result->fetch_assoc()) {
    $tb_lines[] = $row;
}
$stmt->next_result(); // Move to next result set (Totals)

// Consume second result set (Totals)
$result_totals = $stmt->store_result() ? $stmt->get_result() : null; // Check if result set exists
$totals = ['total_debits' => 0, 'total_credits' => 0];
// Since GenerateTrialBalance returns two result sets, we need to handle them carefully.
// If the procedure structure is fixed, the second select is totals.
// However, getting multiple result sets in PHP mysqli can be tricky if not in sync.
// Let's rely on the PHP loop to fetch if available.
if ($stmt->more_results()) {
    $totals_res = $stmt->get_result();
    if ($totals_res) {
        $totals = $totals_res->fetch_assoc();
    }
}

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Trial Balance')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Trial Balance</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Financial Reports</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3 align-items-end">
                                        <div class="col-auto">
                                            <label class="form-label">Fiscal Year</label>
                                            <select class="form-select" name="year">
                                                <?php for ($y = date('Y'); $y >= 2023; $y--): ?>
                                                    <option value="<?php echo $y; ?>" <?php echo $fiscal_year == $y ? 'selected' : ''; ?>><?php echo $y; ?></option>
                                                <?php endfor; ?>
                                            </select>
                                        </div>
                                        <div class="col-auto">
                                            <label class="form-label">Period (Month)</label>
                                            <select class="form-select" name="period">
                                                <?php for ($m = 1; $m <= 12; $m++): ?>
                                                    <option value="<?php echo $m; ?>" <?php echo $fiscal_period == $m ? 'selected' : ''; ?>><?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                                                    </option>
                                                <?php endfor; ?>
                                            </select>
                                        </div>
                                        <div class="col-auto">
                                            <button type="submit" class="btn btn-primary">Generate Report</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Report Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Trial Balance as of Period
                                        <?php echo $fiscal_period . '/' . $fiscal_year; ?></h4>
                                    <div class="flex-shrink-0">
                                        <button class="btn btn-soft-primary btn-sm"
                                            onclick="window.print()">Print</button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <table class="table table-bordered dt-responsive nowrap align-middle"
                                        style="width:100%">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Account Code</th>
                                                <th>Account Name</th>
                                                <th>Type</th>
                                                <th class="text-end">Debit</th>
                                                <th class="text-end">Credit</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($tb_lines as $line): ?>
                                                <tr>
                                                    <td><?php echo $line['account_code']; ?></td>
                                                    <td><?php echo $line['account_name']; ?></td>
                                                    <td><?php echo $line['account_type']; ?></td>
                                                    <td class="text-end">
                                                        <?php echo number_format($line['debit_total'], 2); ?></td>
                                                    <td class="text-end">
                                                        <?php echo number_format($line['credit_total'], 2); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot class="table-light fw-bold">
                                            <tr>
                                                <td colspan="3" class="text-end">TOTALS</td>
                                                <td class="text-end">
                                                    <?php echo number_format($totals['total_debits'] ?? 0, 2); ?></td>
                                                <td class="text-end">
                                                    <?php echo number_format($totals['total_credits'] ?? 0, 2); ?></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>