<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) exit('Unauthorized');

include('../../includes/config.php');

$acct_id = intval($_GET['acct_id'] ?? 0);
$from = $_GET['from_date'] ?? date('Y-m-01');
$to   = $_GET['to_date'] ?? date('Y-m-d');
$store_id = intval($_GET['store_id'] ?? 0);

// Fetch account info
$stmtAcc = $conn->prepare("SELECT account_name FROM accounts WHERE id = ?");
$stmtAcc->bind_param("i", $acct_id);
$stmtAcc->execute();
$accountResult = $stmtAcc->get_result();
$account = $accountResult->fetch_assoc();
$stmtAcc->close();

if (!$account) {
    echo "<p style='color:red; margin-top:20px;'>Invalid Account ID.</p>";
    exit;
}

$where = ["ft.account_id = ?", "ft.transaction_date BETWEEN ? AND ?"];
$params = [$acct_id, $from, $to];
$types = "iss";

if ($store_id > 0) {
    $where[] = "ft.store_id = ?";
    $params[] = $store_id;
    $types .= "i";
}
$whereSql = implode(" AND ", $where);

// Fetch transactions
$sql = "
    SELECT ft.id, ft.transaction_date, ft.type,
           ft.debit, ft.credit, ft.description,
           s.store_name, u.first_name, u.last_name
    FROM financial_transactions ft
    LEFT JOIN stores s ON ft.store_id = s.id
    LEFT JOIN users u ON ft.created_by = u.id
    WHERE $whereSql
    ORDER BY ft.transaction_date, ft.id
";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$txns = $stmt->get_result();

// Totals & grouping
$grouped = [];
$td = $tc = 0;
while ($r = $txns->fetch_assoc()) {
    $month = date('Y-m', strtotime($r['transaction_date']));
    $grouped[$month][] = $r;
    $td += floatval($r['debit']);
    $tc += floatval($r['credit']);
}
?>

<style>
body {
    margin: 0;
    font-family: 'Segoe UI', sans-serif;
    color: #eee;
    background: url('../../images/profile.jpg') no-repeat center center fixed;
    background-size: cover;
}

.card {
    margin: 30px auto;
    padding: 30px;
    max-width: 1850px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 15px;
    backdrop-filter: blur(10px);
}

h3, h4 {
    color: #ffa500;
    margin-top: 0;
}

.filters {
    margin: 15px 0;
}

.filters a {
    text-decoration: none;
    margin-right: 10px;
    color: #ffa500;
    font-weight: bold;
}

.detail-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
    margin-top: 15px;
    background: rgba(255,255,255,0.05);
    border-radius: 8px;
    overflow: hidden;
}

.detail-table th, .detail-table td {
    padding: 10px;
    border-bottom: 1px solid rgba(255,255,255,0.15);
    text-align: left;
}

.detail-table th {
    background: rgba(255,165,0,0.3);
    color: #fff;
}

.detail-table td {
    color: #eee;
}

.detail-table tfoot td {
    font-weight: bold;
    background: rgba(255,255,255,0.1);
}

.no-data {
    margin-top: 20px;
    color: #ccc;
}
</style>

<div class="card">
    <h3>Account Details for <?= htmlspecialchars($account['account_name']) ?></h3>

    <div class="filters">
        <a href="trial_balance_detail_export.php?<?= http_build_query($_GET) ?>&export=csv">Export CSV</a> |
        <a href="trial_balance_detail_export.php?<?= http_build_query($_GET) ?>&export=pdf">Export PDF</a>
    </div>

    <?php if (count($grouped) === 0): ?>
        <p class="no-data">No transactions found for this account in the selected date range and filters.</p>
    <?php else: ?>
        <?php foreach ($grouped as $month => $rows): ?>
            <h4><?= htmlspecialchars(date('F Y', strtotime($month . '-01'))) ?></h4>
            <table class="detail-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Type</th>
                        <th style="text-align:right;">Debit</th>
                        <th style="text-align:right;">Credit</th>
                        <th>Description</th>
                        <th>Store</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $tx): ?>
                        <tr>
                            <td><?= htmlspecialchars($tx['transaction_date']) ?></td>
                            <td><?= ucwords(str_replace('_', ' ', $tx['type'])) ?></td>
                            <td style="text-align:right;"><?= number_format($tx['debit'],2) ?></td>
                            <td style="text-align:right;"><?= number_format($tx['credit'],2) ?></td>
                            <td><?= htmlspecialchars($tx['description']) ?></td>
                            <td><?= htmlspecialchars($tx['store_name']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td><strong>Total <?= htmlspecialchars(date('F Y', strtotime($month . '-01'))) ?></strong></td>
                        <td></td>
                        <td style="text-align:right;"><?= number_format(array_sum(array_column($rows, 'debit')),2) ?></td>
                        <td style="text-align:right;"><?= number_format(array_sum(array_column($rows, 'credit')),2) ?></td>
                        <td colspan="2"></td>
                    </tr>
                </tfoot>
            </table>
        <?php endforeach; ?>

        <h4>Overall Totals</h4>
        <table class="detail-table">
            <thead>
                <tr>
                    <th style="text-align:right;">Total Debits</th>
                    <th style="text-align:right;">Total Credits</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="text-align:right;"><?= number_format($td,2) ?></td>
                    <td style="text-align:right;"><?= number_format($tc,2) ?></td>
                </tr>
            </tbody>
        </table>
    <?php endif; ?>
</div>
