<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Filters
$status_filter = $_GET['status'] ?? '';
$entry_type_filter = $_GET['entry_type'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');

// Build query
$journal_sql = "SELECT je.*, u.full_name as created_by_name,
                       (SELECT COUNT(*) FROM journal_entry_lines WHERE journal_id = je.journal_id) as line_count
                FROM journal_entries je
                LEFT JOIN users u ON je.created_by = u.user_id
                WHERE 1=1";

$params = [];
$types = '';

if (!empty($status_filter)) {
    $journal_sql .= " AND je.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

if (!empty($entry_type_filter)) {
    $journal_sql .= " AND je.entry_type = ?";
    $params[] = $entry_type_filter;
    $types .= 's';
}

$journal_sql .= " AND je.entry_date BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';

$journal_sql .= " ORDER BY je.entry_date DESC, je.journal_id DESC LIMIT 100";

$stmt = $conn->prepare($journal_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$journal_result = $stmt->get_result();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Journal Entries')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .journal-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1rem;
        }
        
        .journal-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
        
        .journal-entry {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
        }
        
        .journal-entry:hover {
            background: #f8fafc;
        }
        
        .journal-entry:last-child {
            border-bottom: none;
        }
        
        .journal-number {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            font-size: 1.1rem;
            color: #1e293b;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .status-draft {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-posted {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-void {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .entry-type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .amount-display {
            font-weight: 700;
            font-size: 1.1rem;
            color: #1e293b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Journal Entries</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Journal Entries</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="journal-card">
                        <div class="journal-header">
                            <h5 class="mb-0"><i class="ri-filter-line me-2"></i>Filters</h5>
                        </div>
                        <div class="card-body">
                            <form method="GET" action="">
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Status</label>
                                        <select class="form-select" name="status">
                                            <option value="">All Statuses</option>
                                            <option value="DRAFT" <?php echo $status_filter === 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                            <option value="POSTED" <?php echo $status_filter === 'POSTED' ? 'selected' : ''; ?>>Posted</option>
                                            <option value="VOID" <?php echo $status_filter === 'VOID' ? 'selected' : ''; ?>>Void</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Entry Type</label>
                                        <select class="form-select" name="entry_type">
                                            <option value="">All Types</option>
                                            <option value="MANUAL" <?php echo $entry_type_filter === 'MANUAL' ? 'selected' : ''; ?>>Manual</option>
                                            <option value="AUTO_PATIENT_REG" <?php echo $entry_type_filter === 'AUTO_PATIENT_REG' ? 'selected' : ''; ?>>Patient Registration</option>
                                            <option value="AUTO_INVOICE" <?php echo $entry_type_filter === 'AUTO_INVOICE' ? 'selected' : ''; ?>>Invoice</option>
                                            <option value="AUTO_PAYMENT" <?php echo $entry_type_filter === 'AUTO_PAYMENT' ? 'selected' : ''; ?>>Payment</option>
                                            <option value="AUTO_EXPENSE" <?php echo $entry_type_filter === 'AUTO_EXPENSE' ? 'selected' : ''; ?>>Expense</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">From Date</label>
                                        <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">To Date</label>
                                        <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Journal Entries List -->
                    <div class="journal-card">
                        <div class="journal-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="ri-file-list-3-line me-2"></i>Journal Entries</h5>
                                <a href="create_journal_entry.php" class="btn btn-light btn-sm">
                                    <i class="ri-add-line me-1"></i>Create Manual Entry
                                </a>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <?php if ($journal_result->num_rows > 0): ?>
                                <?php while ($entry = $journal_result->fetch_assoc()): ?>
                                <div class="journal-entry">
                                    <div class="row align-items-center">
                                        <div class="col-md-2">
                                            <div class="journal-number"><?php echo htmlspecialchars($entry['journal_number']); ?></div>
                                            <small class="text-muted"><?php echo date('d M Y', strtotime($entry['entry_date'])); ?></small>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="fw-medium"><?php echo htmlspecialchars($entry['description']); ?></div>
                                            <div class="d-flex gap-2 mt-1">
                                                <span class="entry-type-badge">
                                                    <?php echo str_replace('AUTO_', '', $entry['entry_type']); ?>
                                                </span>
                                                <?php if ($entry['reference_type']): ?>
                                                <span class="badge bg-secondary">
                                                    <?php echo $entry['reference_type'] . ' #' . $entry['reference_id']; ?>
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <span class="status-badge status-<?php echo strtolower($entry['status']); ?>">
                                                <?php echo $entry['status']; ?>
                                            </span>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <div class="amount-display">
                                                KES <?php echo number_format($entry['total_debit'], 2); ?>
                                            </div>
                                            <small class="text-muted"><?php echo $entry['line_count']; ?> lines</small>
                                        </div>
                                        <div class="col-md-2 text-end">
                                            <button class="btn btn-sm btn-outline-primary" onclick="viewJournalEntry(<?php echo $entry['journal_id']; ?>)">
                                                <i class="ri-eye-line"></i> View
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="ri-file-list-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                    <p class="text-muted mt-2">No journal entries found</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Journal Entry Details Modal -->
    <div class="modal fade" id="journalDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Journal Entry Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="journalDetailsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
    function viewJournalEntry(journalId) {
        $('#journalDetailsModal').modal('show');
        
        $.ajax({
            url: 'ajax/get_journal_entry.php',
            method: 'GET',
            data: { journal_id: journalId },
            success: function(response) {
                $('#journalDetailsContent').html(response);
            },
            error: function() {
                $('#journalDetailsContent').html(
                    '<div class="alert alert-danger">Failed to load journal entry details</div>'
                );
            }
        });
    }
    </script>
</body>
</html>