<?php
session_start();
include '../db.php';
include '../financial_helpers.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo 'Unauthorized';
    exit();
}

$store_id = $_SESSION['store_id'] ?? 1;

if (isset($_GET['id'])) {
    $entry_id = $_GET['id'];
    
    // Get journal entry details
    $stmt = $conn->prepare("
        SELECT 
            je.*,
            COALESCE(u.username, 'System') as created_by_name
        FROM journal_entries je
        LEFT JOIN users u ON je.user_id = u.id
        WHERE je.id = ? AND je.store_id = ?
    ");
    $stmt->bind_param("ii", $entry_id, $store_id);
    $stmt->execute();
    $entry = $stmt->get_result()->fetch_assoc();
    
    if (!$entry) {
        echo '<div class="alert alert-danger">Journal entry not found</div>';
        exit();
    }
    
    // Get journal entry lines
    $stmt = $conn->prepare("
        SELECT 
            jel.*,
            coa.account_code,
            coa.account_name,
            coa.account_type
        FROM journal_entry_lines jel
        JOIN chart_of_accounts coa ON jel.account_id = coa.id
        WHERE jel.journal_entry_id = ?
        ORDER BY jel.id
    ");
    $stmt->bind_param("i", $entry_id);
    $stmt->execute();
    $lines = $stmt->get_result();
    
    // Calculate totals from lines
    $total_debit = 0;
    $total_credit = 0;
    $lines_data = [];
    while ($line = $lines->fetch_assoc()) {
        $total_debit += $line['debit_amount'];
        $total_credit += $line['credit_amount'];
        $lines_data[] = $line;
    }
    
    ?>
    <div class="row">
        <div class="col-md-6">
            <h6>Entry Information</h6>
            <table class="table table-sm">
                <tr>
                    <td><strong>Entry Number:</strong></td>
                    <td><?php echo htmlspecialchars($entry['entry_number']); ?></td>
                </tr>
                <tr>
                    <td><strong>Date:</strong></td>
                    <td><?php echo date('M d, Y', strtotime($entry['entry_date'])); ?></td>
                </tr>
                <tr>
                    <td><strong>Source Type:</strong></td>
                    <td><?php echo ucfirst(str_replace('_', ' ', $entry['source_type'])); ?></td>
                </tr>
                <tr>
                    <td><strong>Status:</strong></td>
                    <td>
                        <span class="badge bg-<?php 
                            echo $entry['status'] === 'draft' ? 'secondary' : 
                                ($entry['status'] === 'posted' ? 'success' : 'danger'); 
                        ?>">
                            <?php echo ucfirst($entry['status']); ?>
                        </span>
                    </td>
                </tr>
                <tr>
                    <td><strong>Created By:</strong></td>
                    <td><?php echo htmlspecialchars($entry['created_by_name'] ?? 'System'); ?></td>
                </tr>
                <tr>
                    <td><strong>Created At:</strong></td>
                    <td><?php echo date('M d, Y H:i', strtotime($entry['created_at'])); ?></td>
                </tr>
                <?php if ($entry['posted_at']): ?>
                <tr>
                    <td><strong>Posted At:</strong></td>
                    <td><?php echo date('M d, Y H:i', strtotime($entry['posted_at'])); ?></td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
        <div class="col-md-6">
            <h6>Summary</h6>
            <table class="table table-sm">
                <tr>
                    <td><strong>Total Debit:</strong></td>
                    <td class="text-end"><?php echo number_format($total_debit, 2); ?></td>
                </tr>
                <tr>
                    <td><strong>Total Credit:</strong></td>
                    <td class="text-end"><?php echo number_format($total_credit, 2); ?></td>
                </tr>
                <tr class="table-<?php echo abs($total_debit - $total_credit) < 0.01 ? 'success' : 'danger'; ?>">
                    <td><strong>Balance:</strong></td>
                    <td class="text-end">
                        <?php 
                        $balance = $total_debit - $total_credit;
                        echo number_format($balance, 2);
                        echo $balance == 0 ? ' (Balanced)' : ' (Not Balanced)';
                        ?>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    
    <div class="mt-3">
        <h6>Description</h6>
        <p><?php echo htmlspecialchars($entry['description']); ?></p>
    </div>
    
    <div class="mt-3">
        <h6>Journal Entry Lines</h6>
        <div class="table-responsive">
            <table class="table table-striped table-sm">
                <thead>
                    <tr>
                        <th>Account Code</th>
                        <th>Account Name</th>
                        <th>Account Type</th>
                        <th class="text-end">Debit Amount</th>
                        <th class="text-end">Credit Amount</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lines_data as $line): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($line['account_code']); ?></td>
                            <td><?php echo htmlspecialchars($line['account_name']); ?></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo $line['account_type'] === 'asset' ? 'primary' : 
                                        ($line['account_type'] === 'liability' ? 'warning' : 
                                        ($line['account_type'] === 'equity' ? 'info' : 
                                        ($line['account_type'] === 'revenue' ? 'success' : 'danger'))); 
                                ?>">
                                    <?php echo ucfirst($line['account_type']); ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <?php echo $line['debit_amount'] > 0 ? number_format($line['debit_amount'], 2) : '-'; ?>
                            </td>
                            <td class="text-end">
                                <?php echo $line['credit_amount'] > 0 ? number_format($line['credit_amount'], 2) : '-'; ?>
                            </td>
                            <td><?php echo htmlspecialchars($line['description']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php
} else {
    echo '<div class="alert alert-danger">Entry ID required</div>';
}
?>
