<?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');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    echo "<p style='color:red;'>Invalid Journal Entry ID.</p>";
    include('../../includes/footer.php');
    exit();
}

// Fetch journal header
$stmt = $conn->prepare("
    SELECT je.*, 
           s.store_name, 
           u.first_name, u.last_name
    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 je.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$entry = $result->fetch_assoc();
$stmt->close();

if (!$entry) {
    echo "<p style='color:red;'>Journal Entry not found.</p>";
    include('../../includes/footer.php');
    exit();
}

// Normalize status for consistent use
$status = strtolower(trim($entry['status'] ?? ''));

// Fetch journal lines
$lines = [];
$lines_stmt = $conn->prepare("
    SELECT jel.*, a.account_name 
    FROM journal_lines jel
    LEFT JOIN accounts a ON jel.account_id = a.id
    WHERE jel.je_id = ?
");
$lines_stmt->bind_param("i", $id);
$lines_stmt->execute();
$lines_result = $lines_stmt->get_result();
while ($line = $lines_result->fetch_assoc()) {
    $lines[] = $line;
}
$lines_stmt->close();
?>

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

.container {
    max-width: 1000px;
    margin: 60px auto;
    background: rgba(255,255,255,0.08);
    padding: 30px;
    border-radius: 15px;
}

h2 {
    color: #ffa500;
    margin-bottom: 20px;
}

.detail-row {
    margin-bottom: 10px;
}

.detail-label {
    font-weight: bold;
    width: 180px;
    display: inline-block;
}

.action-buttons a {
    background: rgba(255,165,0,0.3);
    color: #fff;
    padding: 8px 12px;
    border-radius: 8px;
    margin-right: 10px;
    text-decoration: none;
}

.action-buttons a:hover {
    background: rgba(255,165,0,0.6);
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    background: rgba(255,255,255,0.05);
}

th, td {
    padding: 10px;
    border: 1px solid rgba(255,255,255,0.2);
    text-align: left;
}
</style>

<div class="container">
    <h2>Journal Entry Details</h2>

    <div class="detail-row"><span class="detail-label">Entry Date:</span> <?= htmlspecialchars($entry['entry_date']) ?></div>
    <div class="detail-row"><span class="detail-label">Description:</span> <?= htmlspecialchars($entry['description']) ?></div>
    <div class="detail-row"><span class="detail-label">Store:</span> <?= htmlspecialchars($entry['store_name']) ?></div>
    <div class="detail-row"><span class="detail-label">Status:</span> <?= htmlspecialchars(ucfirst($status)) ?></div>
    <div class="detail-row"><span class="detail-label">Created By:</span> <?= htmlspecialchars($entry['first_name'] . ' ' . $entry['last_name']) ?></div>
    <div class="detail-row"><span class="detail-label">Created At:</span> <?= htmlspecialchars($entry['created_at']) ?></div>

    <h3 style="margin-top:25px;">Journal Lines</h3>

    <table>
        <thead>
            <tr>
                <th>Account</th>
                <th>Debit</th>
                <th>Credit</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $total_debit = 0;
            $total_credit = 0;
            foreach ($lines as $line): 
                $total_debit += $line['debit'];
                $total_credit += $line['credit'];
            ?>
            <tr>
                <td><?= htmlspecialchars($line['account_name']) ?></td>
                <td><?= number_format($line['debit'], 2) ?></td>
                <td><?= number_format($line['credit'], 2) ?></td>
                <td><?= htmlspecialchars($line['description']) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <th style="text-align:right;">Total:</th>
                <th><?= number_format($total_debit, 2) ?></th>
                <th><?= number_format($total_credit, 2) ?></th>
                <th></th>
            </tr>
        </tfoot>
    </table>

    <div class="action-buttons" style="margin-top:25px;">
        <a href="journal_entry_edit.php?id=<?= $entry['id'] ?>">Edit</a>
        <a href="journal_entry_delete.php?id=<?= $entry['id'] ?>" onclick="return confirm('Are you sure you want to delete this journal entry?');">Delete</a>
        <a href="journal_entries.php">Back to List</a>

        <?php if ($status === 'draft'): ?>
            <a href="post_journal_entry.php?id=<?= $entry['id'] ?>" onclick="return confirm('Are you sure you want to post this journal entry? This cannot be undone.')">
                ✅ Post Journal
            </a>
        <?php else: ?>
            <span style="background: rgba(34,197,94,0.2); padding:8px 12px; border-radius:8px;">✅ Already Posted</span>
        <?php endif; ?>
    </div>
</div>

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