<?php
session_start();
ob_start();  // Start output buffering

if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    header("Location: ../../index.php");
    exit();
}

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

// Handle Delete
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $del_id = (int)$_GET['delete_id'];
    $stmtDel = $conn->prepare("UPDATE financial_transactions SET status = 'voided' WHERE id = ?");
    $stmtDel->bind_param("i", $del_id);
    $stmtDel->execute();
    $stmtDel->close();
    header("Location: transactions.php?msg=Transaction+voided");
    exit();
}

// Filtering
$filter_store = $_GET['store_id'] ?? '';
$filter_type = $_GET['type'] ?? '';

$whereClauses = ["ft.status = 'approved'"];
$params = [];
$paramTypes = "";

if ($filter_store !== '' && is_numeric($filter_store)) {
    $whereClauses[] = "ft.store_id = ?";
    $params[] = $filter_store;
    $paramTypes .= "i";
}

if ($filter_type !== '') {
    $whereClauses[] = "ft.type = ?";
    $params[] = $filter_type;
    $paramTypes .= "s";
}

$whereSql = implode(" AND ", $whereClauses);

// Totals per type
$sqlTotals = "
    SELECT ft.type, 
           SUM(CASE WHEN ft.debit > 0 THEN ft.debit ELSE 0 END) AS total_debit,
           SUM(CASE WHEN ft.credit > 0 THEN ft.credit ELSE 0 END) AS total_credit
    FROM financial_transactions ft
    WHERE $whereSql
    GROUP BY ft.type
";

$stmtTotals = $conn->prepare($sqlTotals);
if ($paramTypes) $stmtTotals->bind_param($paramTypes, ...$params);
$stmtTotals->execute();
$resultTotals = $stmtTotals->get_result();

$totals = [];
$grandDebit = 0;
$grandCredit = 0;

while ($row = $resultTotals->fetch_assoc()) {
    $totals[$row['type']] = [
        'debit' => $row['total_debit'],
        'credit' => $row['total_credit']
    ];
    $grandDebit += $row['total_debit'];
    $grandCredit += $row['total_credit'];
}
$stmtTotals->close();

// Pagination
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$countStmt = $conn->prepare("SELECT COUNT(*) FROM financial_transactions ft WHERE $whereSql");
if ($paramTypes) $countStmt->bind_param($paramTypes, ...$params);
$countStmt->execute();
$countStmt->bind_result($total_records);
$countStmt->fetch();
$countStmt->close();

$total_pages = ceil($total_records / $limit);

// Fetch Records
$sql = "
    SELECT ft.id, ft.transaction_date, ft.type, ft.amount, ft.payment_method, ft.account, 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 DESC, ft.id DESC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($sql);

if ($paramTypes) {
    $paramTypesWithLimit = $paramTypes . "ii";
    $stmt->bind_param($paramTypesWithLimit, ...array_merge($params, [$limit, $offset]));
} else {
    $stmt->bind_param("ii", $limit, $offset);
}

$stmt->execute();
$result = $stmt->get_result();

$page_title = "Financial Transactions";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title><?= htmlspecialchars($page_title) ?></title>
    <link rel="icon" type="image/png" href="../../images/logo.png" />
    <style>
    body {
        margin: 0;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        font-family: 'Segoe UI', sans-serif;
        color: #eee;
    }
    .content {
        margin: 2rem auto 0 auto;
        padding: 40px;
        max-width: 1850px;
    }
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }
    h1.page-title {
        color: #ffa500;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 700;
        font-size: 2rem;
    }
    h1.page-title img {
        height: 40px;
        width: auto;
    }
    a.back-link {
        color: #ffa500;
        text-decoration: none;
        font-weight: 600;
        border: 1.5px solid #ffa500;
        padding: 6px 14px;
        border-radius: 8px;
        transition: background-color 0.3s ease, color 0.3s ease;
        white-space: nowrap;
    }
    a.back-link:hover {
        background-color: #ffa500;
        color: #222;
    }
    h2 { color: #ffa500; margin-bottom: 20px; }
    .filter-form {
        margin: 20px 0;
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
    }
    .filter-form select,
    .filter-form button,
    .btn-action {
        padding: 8px 12px;
        border-radius: 8px;
        border: none;
        font-weight: 500;
    }
    .filter-form button {
        background: #ffa500;
        color: #222;
        cursor: pointer;
    }
    .btn-action {
        background: #ffa500;
        color: #222;
        text-decoration: none;
        margin-left: auto;
    }
    .summary {
        background: rgba(255,255,255,0.1);
        padding: 10px 15px;
        border-radius: 10px;
        font-size: 14px;
        margin-bottom: 20px;
    }
    .card {
        background: rgba(255,255,255,0.1);
        border-radius: 15px;
        padding: 20px;
        margin-top: 20px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }
    table th, table td {
        padding: 10px 12px;
        border-bottom: 1px solid rgba(255,255,255,0.2);
        text-align: left;
    }
    table th:nth-child(3),
    table td:nth-child(3) {
        text-align: right;
    }
    table th {
        background: rgba(255,165,0,0.3);
        color: #fff;
    }
    .pagination {
        text-align: center;
        margin-top: 20px;
    }
    .pagination a,
    .pagination span.current-page {
        margin: 0 5px;
        padding: 8px 12px;
        background: rgba(255,165,0,0.7);
        border-radius: 5px;
        text-decoration: none;
        color: #222;
        font-weight: bold;
    }
    </style>
</head>
<body>

<div class="content">

    <div class="page-header">
        <h1 class="page-title">
            <img src="../../images/logo.png" alt="Logo" />
            <?= htmlspecialchars($page_title) ?>
        </h1>
        <a href="reports_dashboard.php" class="back-link">&laquo; Back to Reports Dashboard</a>
    </div>

    <form class="filter-form" method="GET">
        <select name="store_id">
            <option value="">-- All Stores --</option>
            <?php
            $stores = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL");
            while ($store = $stores->fetch_assoc()) {
                $sel = ($filter_store == $store['id']) ? 'selected' : '';
                echo "<option value='{$store['id']}' {$sel}>{$store['store_name']}</option>";
            }
            ?>
        </select>
        <select name="type">
            <option value="">-- All Types --</option>
            <?php
            $types = ['deposit', 'withdrawal', 'expense', 'cogs', 'loan', 'repayment', 'sale_income', 'supplier_payment', 'transfer'];
            foreach ($types as $t) {
                $sel = ($filter_type == $t) ? 'selected' : '';
                echo "<option value='{$t}' {$sel}>" . ucwords(str_replace('_',' ',$t)) . "</option>";
            }
            ?>
        </select>
        <button type="submit">Filter</button>
        <a href="?<?= http_build_query(array_merge($_GET, ['export'=>'csv', 'page'=>1])) ?>" class="btn-action">Export CSV</a>
        <a href="?<?= http_build_query(array_merge($_GET, ['export'=>'pdf', 'page'=>1])) ?>" class="btn-action">Export PDF</a>
    </form>

    <div class="summary">
        <table>
            <tr>
                <th>Transaction Type</th>
                <th>Total Debits</th>
                <th>Total Credits</th>
            </tr>
            <?php foreach ($totals as $type => $amounts): ?>
                <tr>
                    <td><?= ucwords(str_replace('_',' ',$type)) ?></td>
                    <td><?= number_format($amounts['debit'], 2) ?></td>
                    <td><?= number_format($amounts['credit'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
            <tr style="font-weight:bold; background: rgba(255,165,0,0.2);">
                <td>Grand Totals</td>
                <td><?= number_format($grandDebit,2) ?></td>
                <td><?= number_format($grandCredit,2) ?></td>
            </tr>
        </table>
    </div>

    <?php if (isset($_GET['msg'])): ?>
        <div style="background:rgba(16,185,129,0.2); padding:10px 15px; margin-bottom:20px; border-radius:8px;">
            <?= htmlspecialchars($_GET['msg']) ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Payment Method</th>
                    <th>Account</th>
                    <th>Store</th>
                    <th>Description</th>
                    <th>Created By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($result->num_rows): ?>
                <?php while($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['transaction_date']) ?></td>
                        <td><?= ucwords(str_replace('_',' ',$row['type'])) ?></td>
                        <td><?= number_format($row['amount'],2) ?></td>
                        <td><?= ucwords($row['payment_method']) ?></td>
                        <td><?= htmlspecialchars($row['account']) ?></td>
                        <td><?= htmlspecialchars($row['store_name']) ?></td>
                        <td><?= htmlspecialchars($row['description']) ?></td>
                        <td><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></td>
                        <td><a href="transaction_detail.php?id=<?= $row['id'] ?>" style="color:#ffa500;">View</a></td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="9" style="text-align:center;">No transactions found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>

        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">&laquo; Prev</a>
            <?php endif; ?>
            <span class="current-page"><?= $page ?></span>
            <?php if ($page < $total_pages): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">Next &raquo;</a>
            <?php endif; ?>
        </div>
    </div>

</div>

<?php include('../../includes/footer.php'); ob_end_flush(); ?>
</body>
</html>
