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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get filter parameters
$account_id = $_GET['account_id'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');

// Fetch accounts for filter
$accounts_sql = "SELECT account_id, account_code, account_name 
                 FROM chart_of_accounts 
                 WHERE is_active = 1 AND is_header = 0
                 ORDER BY account_code";
$accounts_result = $conn->query($accounts_sql);

// Build ledger query
$ledger_sql = "SELECT * FROM account_ledger_view WHERE 1=1";
$params = [];
$types = '';

if (!empty($account_id)) {
    $ledger_sql .= " AND account_id = ?";
    $params[] = $account_id;
    $types .= 'i';
}

$ledger_sql .= " AND transaction_date BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';

$ledger_sql .= " ORDER BY transaction_date DESC, ledger_id DESC LIMIT 500";

$stmt = $conn->prepare($ledger_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$ledger_result = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'General Ledger')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .ledger-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .ledger-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
        
        .ledger-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .ledger-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .ledger-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .ledger-table tr:hover {
            background: #f8fafc;
        }
        
        .amount-debit {
            color: #059669;
            font-weight: 600;
        }
        
        .amount-credit {
            color: #dc2626;
            font-weight: 600;
        }
        
        .balance {
            font-weight: 700;
            color: #1e293b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <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">General Ledger</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">General Ledger</li>
                                    </ol>
                                    </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="ledger-card mb-4">
                        <div class="ledger-header">
                            <h5 class="mb-0"><i class="ri-filter-line me-2"></i>Filters</h5>
                        </div>
                        <div class="card-body">
                            <form method="GET" action="" id="filterForm">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Account</label>
                                        <select class="form-select" name="account_id">
                                            <option value="">All Accounts</option>
                                            <?php 
                                            $accounts_result->data_seek(0);
                                            while ($account = $accounts_result->fetch_assoc()): 
                                            ?>
                                                <option value="<?php echo $account['account_id']; ?>" 
                                                        <?php echo $account_id == $account['account_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($account['account_code'] . ' - ' . $account['account_name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">From Date</label>
                                        <input type="date" class="form-control" name="date_from" 
                                               value="<?php echo $date_from; ?>">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">To Date</label>
                                        <input type="date" class="form-control" name="date_to" 
                                               value="<?php echo $date_to; ?>">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Ledger Entries -->
                    <div class="ledger-card">
                        <div class="ledger-header">
                            <h5 class="mb-0"><i class="ri-file-list-3-line me-2"></i>Ledger Entries</h5>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="ledger-table">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Account</th>
                                            <th>Journal #</th>
                                            <th>Description</th>
                                            <th style="text-align: right;">Debit</th>
                                            <th style="text-align: right;">Credit</th>
                                            <th style="text-align: right;">Balance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($ledger_result->num_rows > 0): ?>
                                            <?php while ($entry = $ledger_result->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo date('d M Y', strtotime($entry['transaction_date'])); ?></td>
                                                <td>
                                                    <div style="font-size: 0.875rem; color: #64748b;">
                                                        <?php echo htmlspecialchars($entry['account_code']); ?>
                                                    </div>
                                                    <div style="font-weight: 500;">
                                                        <?php echo htmlspecialchars($entry['account_name']); ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary">
                                                        <?php echo htmlspecialchars($entry['journal_number']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo htmlspecialchars($entry['description']); ?></td>
                                                <td style="text-align: right;">
                                                    <?php if ($entry['debit_amount'] > 0): ?>
                                                        <span class="amount-debit">
                                                            KES <?php echo number_format($entry['debit_amount'], 2); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="text-align: right;">
                                                    <?php if ($entry['credit_amount'] > 0): ?>
                                                        <span class="amount-credit">
                                                            KES <?php echo number_format($entry['credit_amount'], 2); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="text-align: right;">
                                                    <span class="balance">
                                                        KES <?php echo number_format($entry['running_balance'], 2); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="7" class="text-center py-4">
                                                    <i class="ri-file-list-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                                    <p class="text-muted mt-2">No ledger entries found for the selected criteria</p>
                                                </td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>