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

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

// Filters
$filter_store = $_GET['store_id'] ?? '';
$filter_status = $_GET['status'] ?? '';
$where = [];
$params = [];
$types = '';

if ($filter_store !== '') {
    $where[] = "je.store_id = ?";
    $params[] = $filter_store;
    $types .= 'i';
}
if ($filter_status !== '') {
    $where[] = "je.status = ?";
    $params[] = $filter_status;
    $types .= 's';
}
$whereSql = $where ? implode(' AND ', $where) : '1=1';

// Fetch Entries with subqueries for debit/credit accounts and amounts
$sql = "
SELECT 
    je.*,
    s.store_name,
    u.first_name, u.last_name,
    -- Debit Account ID (from first debit journal line)
    (SELECT jl.account_id FROM journal_lines jl WHERE jl.je_id = je.id AND jl.debit > 0 LIMIT 1) AS debit_account_id,
    -- Credit Account ID (from first credit journal line)
    (SELECT jl.account_id FROM journal_lines jl WHERE jl.je_id = je.id AND jl.credit > 0 LIMIT 1) AS credit_account_id,
    -- Debit Account Name
    (SELECT a.account_name FROM accounts a WHERE a.id = 
        (SELECT jl.account_id FROM journal_lines jl WHERE jl.je_id = je.id AND jl.debit > 0 LIMIT 1)
    ) AS debit_account,
    -- Credit Account Name
    (SELECT a.account_name FROM accounts a WHERE a.id = 
        (SELECT jl.account_id FROM journal_lines jl WHERE jl.je_id = je.id AND jl.credit > 0 LIMIT 1)
    ) AS credit_account,
    -- Sum Debit Amount
    (SELECT IFNULL(SUM(jl.debit),0) FROM journal_lines jl WHERE jl.je_id = je.id) AS debit_amount,
    -- Sum Credit Amount
    (SELECT IFNULL(SUM(jl.credit),0) FROM journal_lines jl WHERE jl.je_id = je.id) AS credit_amount
FROM journal_entries je
LEFT JOIN stores s ON je.store_id = s.id
LEFT JOIN users u ON je.created_by = u.id
WHERE $whereSql
ORDER BY je.entry_date DESC, je.id DESC
";

$stmt = $conn->prepare($sql);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// CSV Export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=journal_entries.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Date', 'Description', 'Debit Account', 'Credit Account', 'Debit', 'Credit', 'Store', 'Status', 'Created By']);
    foreach ($rows as $r) {
        $status = trim(strtolower($r['status'] ?? ''));
        fputcsv($out, [
            $r['entry_date'],
            $r['description'],
            $r['debit_account'],
            $r['credit_account'],
            number_format($r['debit_amount'], 2),
            number_format($r['credit_amount'], 2),
            $r['store_name'],
            ucfirst($status),
            $r['first_name'] . ' ' . $r['last_name']
        ]);
    }
    fclose($out);
    exit();
}

// PDF Export (HTML printable)
if (isset($_GET['export']) && $_GET['export'] === 'pdf') {
    echo "<h2>Journal Entries PDF Export</h2>";
    echo "<table border='1' cellpadding='5' cellspacing='0' style='width:100%;'>";
    echo "<tr><th>Date</th><th>Description</th><th>Debit Account</th><th>Credit Account</th><th>Debit Amt</th><th>Credit Amt</th><th>Store</th><th>Status</th><th>By</th></tr>";
    foreach ($rows as $r) {
        $status = trim(strtolower($r['status'] ?? ''));
        echo "<tr>
            <td>" . htmlspecialchars($r['entry_date']) . "</td>
            <td>" . htmlspecialchars($r['description']) . "</td>
            <td>" . htmlspecialchars($r['debit_account']) . "</td>
            <td>" . htmlspecialchars($r['credit_account']) . "</td>
            <td style='text-align:right;'>" . number_format($r['debit_amount'], 2) . "</td>
            <td style='text-align:right;'>" . number_format($r['credit_amount'], 2) . "</td>
            <td>" . htmlspecialchars($r['store_name']) . "</td>
            <td>" . htmlspecialchars(ucfirst($status)) . "</td>
            <td>" . htmlspecialchars($r['first_name'] . ' ' . $r['last_name']) . "</td>
        </tr>";
    }
    echo "</table>";
    exit();
}

$page_title = "Journal Entries";
?>

<!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;
    }
    .table-card {
        background: rgba(255,255,255,0.1);
        border-radius: 15px;
        padding: 20px;
        margin-top: 20px;
        overflow-x: auto;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }
    th, td {
        padding: 10px 12px;
        border-bottom: 1px solid rgba(255,255,255,0.2);
        text-align: left;
        vertical-align: middle;
    }
    th {
        background: rgba(255,165,0,0.3);
        color: #fff;
    }
    td:nth-child(5),
    td:nth-child(6) {
        text-align: right;
    }
    a.btn {
        color: #ffa500;
        text-decoration: none;
        font-weight: bold;
        margin-right: 10px;
        white-space: nowrap;
    }
    .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 method="GET" class="filter-form">
        <select name="store_id">
            <option value="">-- All Stores --</option>
            <?php
            $storeQ = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL");
            while ($s = $storeQ->fetch_assoc()) {
                $sel = ($filter_store == $s['id']) ? 'selected' : '';
                echo "<option value='{$s['id']}' {$sel}>" . htmlspecialchars($s['store_name']) . "</option>";
            }
            ?>
        </select>
        <select name="status">
            <option value="">-- All Status --</option>
            <option value="draft" <?= $filter_status == 'draft' ? 'selected' : '' ?>>Draft</option>
            <option value="posted" <?= $filter_status == 'posted' ? 'selected' : '' ?>>Posted</option>
        </select>
        <button type="submit">Filter</button>
        <a href="journal_entry_form.php" class="btn-action">+ New Entry</a>
        <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" target="_blank">Export PDF</a>
    </form>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Description</th>
                    <th>Debit Account</th>
                    <th>Credit Account</th>
                    <th>Debit</th>
                    <th>Credit</th>
                    <th>Store</th>
                    <th>Status</th>
                    <th>Created By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($rows) > 0): ?>
                    <?php foreach ($rows as $r):
                        $status = trim(strtolower($r['status'] ?? ''));
                    ?>
                        <tr>
                            <td><?= htmlspecialchars($r['entry_date']) ?></td>
                            <td><?= htmlspecialchars($r['description']) ?></td>
                            <td><a href="trial_balance_detail.php?acct_id=<?= $r['debit_account_id'] ?>" class="btn"><?= htmlspecialchars($r['debit_account']) ?></a></td>
                            <td><a href="trial_balance_detail.php?acct_id=<?= $r['credit_account_id'] ?>" class="btn"><?= htmlspecialchars($r['credit_account']) ?></a></td>
                            <td style="text-align:right;"><?= number_format($r['debit_amount'], 2) ?></td>
                            <td style="text-align:right;"><?= number_format($r['credit_amount'], 2) ?></td>
                            <td><?= htmlspecialchars($r['store_name']) ?></td>
                            <td><?= htmlspecialchars(ucfirst($status)) ?></td>
                            <td><?= htmlspecialchars($r['first_name'] . ' ' . $r['last_name']) ?></td>
                            <td>
                                <a class="btn" href="journal_entry_view.php?id=<?= $r['id'] ?>">View</a>
                                <?php if ($status === 'draft'): ?>
                                    <a class="btn" href="journal_entry_edit.php?id=<?= $r['id'] ?>">Edit</a>
                                    <a class="btn" href="journal_entry_delete.php?id=<?= $r['id'] ?>" onclick="return confirm('Are you sure you want to delete this entry?')">Delete</a>
                                    <a class="btn" href="post_journal_entry.php?id=<?= $r['id'] ?>" onclick="return confirm('Post this journal entry? This action is final.')">Post</a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="10" style="text-align:center;">No journal entries found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Pagination if needed, add if your code has pagination -->
        <?php if (isset($page) && isset($total_pages)): ?>
        <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>
        <?php endif; ?>
    </div>

</div>

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