<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once '../../dripend/includes/db.php';

// Safe query execution wrapper for the new architecture
function getScalar($conn, $query, $key, $default = 0) {
    $res = $conn->query($query);
    return $res ? (float)($res->fetch_assoc()[$key] ?? $default) : $default;
}

$today = date('Y-m-d');

// 1. Core KPIs
$today_collection = getScalar($conn, "SELECT SUM(amount) as val FROM billing_payments WHERE DATE(created_at) = '$today'", 'val');
$total_outstanding = getScalar($conn, "SELECT SUM(total_amount - amount_paid) as val FROM billing_invoices WHERE status IN ('unpaid', 'partial')", 'val');
$today_invoices = getScalar($conn, "SELECT COUNT(id) as val FROM billing_invoices WHERE DATE(created_at) = '$today'", 'val');
$month_collection = getScalar($conn, "SELECT SUM(amount) as val FROM billing_payments WHERE MONTH(created_at) = MONTH('$today') AND YEAR(created_at) = YEAR('$today')", 'val');

// 2. Departmental Revenue Breakdown (Today)
$dept_revenue = [];
$qDept = $conn->query("
    SELECT i.department, SUM(i.total_price) as gross_revenue 
    FROM billing_items i
    JOIN billing_invoices inv ON i.invoice_id = inv.id
    WHERE DATE(inv.created_at) = '$today'
    GROUP BY i.department
    ORDER BY gross_revenue DESC
");
if ($qDept) {
    while($row = $qDept->fetch_assoc()) {
        $dept_revenue[] = $row;
    }
}

// 3. Last 7 Days Revenue Trend (For Chart.js)
$chart_labels = [];
$chart_data = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $chart_labels[] = date('D, M d', strtotime($date));
    $chart_data[] = getScalar($conn, "SELECT SUM(amount) as val FROM billing_payments WHERE DATE(created_at) = '$date'", 'val');
}

// 4. Recent Unpaid/Partial Invoices (Actionable Queue)
$recent_invoices = [];
$qRecent = $conn->query("
    SELECT inv.id, inv.total_amount, inv.amount_paid, inv.status, inv.created_at, p.first_name, p.last_name, p.patient_no 
    FROM billing_invoices inv
    LEFT JOIN patient p ON inv.patient_id = p.id
    WHERE inv.status IN ('unpaid', 'partial')
    ORDER BY inv.created_at DESC LIMIT 10
");
if ($qRecent) {
    while($row = $qRecent->fetch_assoc()) $recent_invoices[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Financial Command Center | eRHAMS Accounts</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        body { background-color: #f1f5f9; margin: 0; font-family: 'Inter', sans-serif; }
        .main-content-wrapper { margin-left: 260px; padding: 2.5rem; width: calc(100% - 260px); min-height: 100vh; }
        @media (max-width: 992px) { .main-content-wrapper { margin-left: 0; width: 100%; padding: 1.5rem; } }
        
        .desk-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;}
        .content-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.02); }
        
        .kpi-card { border-radius: 16px; padding: 25px; border: none; position: relative; overflow: hidden; display: flex; flex-direction: column; justify-content: center; }
        .kpi-card .icon-bg { position: absolute; right: -15px; bottom: -20px; font-size: 100px; opacity: 0.1; transform: rotate(-15deg); }
        .kpi-value { font-size: 32px; font-weight: 800; margin: 10px 0 5px 0; letter-spacing: -1px; }
        
        .table-custom thead th { background: #f8fafc; color: #475569; padding: 15px; font-weight: 800; font-size: 12px; text-transform: uppercase; border-bottom: 1px solid #e2e8f0; }
        .table-custom tbody td { padding: 15px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; color: #334155; font-weight: 500; }
        
        .select2-container .select2-selection--single { height: 50px; border-radius: 12px; border: 1px solid #cbd5e1; padding: 10px 15px; font-weight: 600; font-size: 15px; }
        .select2-container--default .select2-selection--single .select2-selection__arrow { height: 48px; right: 15px; }
        
        .dept-revenue-item { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; border-bottom: 1px solid #f1f5f9; }
        .dept-revenue-item:last-child { border-bottom: none; }
    </style>
</head>
<body>

<?php include '../../dripend/statpages/sidebar.php'; ?>

<div class="main-content-wrapper">
    <div class="desk-header">
        <div>
            <h3 class="fw-bold text-dark m-0" style="letter-spacing: -1px;"><i class="fa-solid fa-vault text-primary me-2"></i> Financial Command Center</h3>
            <p class="text-muted small fw-bold mt-1 mb-0">Overview of universal hospital revenue and outstanding receivables.</p>
        </div>
        <div class="bg-white px-4 py-2 rounded-pill border shadow-sm fw-bold text-dark">
            <i class="fa-solid fa-calendar-day text-primary me-2"></i> <?php echo date('l, F jS, Y'); ?>
        </div>
    </div>

    <!-- KPI ROW -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="kpi-card bg-primary text-white shadow-sm">
                <i class="fa-solid fa-sack-dollar icon-bg"></i>
                <span class="fw-bold text-uppercase small text-white-50">Today's Collection</span>
                <div class="kpi-value">GHS <?php echo number_format($today_collection, 2); ?></div>
                <span class="small fw-bold"><i class="fa-solid fa-arrow-trend-up me-1"></i> Cash & Digital</span>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card bg-danger text-white shadow-sm">
                <i class="fa-solid fa-file-invoice-dollar icon-bg"></i>
                <span class="fw-bold text-uppercase small text-white-50">Pending Receivables</span>
                <div class="kpi-value">GHS <?php echo number_format($total_outstanding, 2); ?></div>
                <span class="small fw-bold"><i class="fa-solid fa-triangle-exclamation me-1"></i> Unpaid & Partial</span>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card bg-info text-white shadow-sm">
                <i class="fa-solid fa-receipt icon-bg"></i>
                <span class="fw-bold text-uppercase small text-white-50">Invoices Generated Today</span>
                <div class="kpi-value"><?php echo number_format($today_invoices); ?></div>
                <span class="small fw-bold"><i class="fa-solid fa-layer-group me-1"></i> Total Encounters Billed</span>
            </div>
        </div>
        <div class="col-md-3">
            <div class="kpi-card bg-dark text-white shadow-sm">
                <i class="fa-solid fa-chart-pie icon-bg"></i>
                <span class="fw-bold text-uppercase small text-white-50">Monthly Collection MTD</span>
                <div class="kpi-value">GHS <?php echo number_format($month_collection, 2); ?></div>
                <span class="small fw-bold"><i class="fa-solid fa-calendar me-1"></i> Month-to-Date</span>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <!-- MAIN LEFT COLUMN -->
        <div class="col-lg-8">
            <!-- REVENUE CHART -->
            <div class="content-card p-4 mb-4">
                <div class="d-flex justify-content-between align-items-center mb-4 border-bottom pb-3">
                    <h6 class="fw-bold text-dark text-uppercase m-0"><i class="fa-solid fa-chart-area text-primary me-2"></i> 7-Day Revenue Trend</h6>
                </div>
                <div style="height: 300px;">
                    <canvas id="revenueChart"></canvas>
                </div>
            </div>

            <!-- UNPAID INVOICES QUEUE -->
            <div class="content-card p-0 overflow-hidden">
                <div class="p-4 border-bottom d-flex justify-content-between align-items-center bg-light">
                    <h6 class="fw-bold text-danger text-uppercase m-0"><i class="fa-solid fa-clock-rotate-left me-2"></i> Action Required: Pending Invoices</h6>
                    <a href="pending_bills.php" class="btn btn-sm btn-outline-dark fw-bold">View All Pending</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-custom mb-0">
                        <thead>
                            <tr>
                                <th>Invoice ID</th>
                                <th>Patient Name</th>
                                <th>Date Issued</th>
                                <th>Total Bill</th>
                                <th>Balance Due</th>
                                <th>Status</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($recent_invoices)): ?>
                                <tr><td colspan="7" class="text-center py-5 text-muted"><i class="fa-solid fa-check-circle fa-3x mb-3 text-success opacity-50"></i><br><span class="fw-bold">All caught up! No pending bills.</span></td></tr>
                            <?php else: ?>
                                <?php foreach($recent_invoices as $inv): 
                                    $bal = $inv['total_amount'] - $inv['amount_paid'];
                                    $badge = $inv['status'] === 'partial' ? 'bg-warning text-dark' : 'bg-danger text-white';
                                ?>
                                <tr>
                                    <td class="fw-bold text-primary">#INV-<?php echo str_pad($inv['id'], 6, '0', STR_PAD_LEFT); ?></td>
                                    <td>
                                        <div class="fw-bold text-dark"><?php echo htmlspecialchars($inv['first_name'] . ' ' . $inv['last_name']); ?></div>
                                        <div class="small text-muted"><?php echo htmlspecialchars($inv['patient_no']); ?></div>
                                    </td>
                                    <td><?php echo date('M d, Y', strtotime($inv['created_at'])); ?></td>
                                    <td class="fw-bold">GHS <?php echo number_format($inv['total_amount'], 2); ?></td>
                                    <td class="fw-bold text-danger">GHS <?php echo number_format($bal, 2); ?></td>
                                    <td><span class="badge <?php echo $badge; ?> rounded-pill px-3"><?php echo strtoupper($inv['status']); ?></span></td>
                                    <td class="text-end">
                                        <!-- Routes to the universal patient billing desk -->
                                        <a href="patientBilling.php?patient_id=<?php echo $inv['patient_no']; ?>" class="btn btn-sm btn-dark fw-bold shadow-sm"><i class="fa-solid fa-cash-register me-1"></i> Pay Now</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- SIDEBAR RIGHT COLUMN -->
        <div class="col-lg-4">
            
            <!-- QUICK BILLING ACTIONS -->
            <div class="content-card p-4 mb-4 border-primary border-top border-4">
                <h6 class="fw-bold text-primary text-uppercase mb-3"><i class="fa-solid fa-bolt me-2"></i> Quick Actions</h6>
                
                <label class="small fw-bold text-muted mb-2">Search Patient to Process Bill</label>
                <select id="patient_search" class="form-select w-100 mb-3"></select>
                
                <hr class="my-3 border-secondary border-opacity-25">
                
                <div class="d-grid gap-2">
                    <!-- Links to future standalone modular pages -->
                    <a href="patientBilling.php" class="btn btn-light border fw-bold text-start p-3 shadow-sm text-dark hover-primary"><i class="fa-solid fa-file-invoice me-3 text-primary"></i> Create Ad-Hoc / Manual Bill</a>
                    <a href="print_payment.php" class="btn btn-light border fw-bold text-start p-3 shadow-sm text-dark hover-primary"><i class="fa-solid fa-print me-3 text-info"></i> Reprint Receipt / Invoice</a>
                </div>
            </div>

            <!-- DEPARTMENTAL REVENUE (TODAY) -->
            <div class="content-card p-4">
                <h6 class="fw-bold text-dark text-uppercase mb-4 pb-2 border-bottom"><i class="fa-solid fa-network-wired text-success me-2"></i> Today's Gross by Dept</h6>
                
                <?php if(empty($dept_revenue)): ?>
                    <div class="text-center py-4 text-muted small fw-bold">No revenue generated today.</div>
                <?php else: ?>
                    <?php 
                        $icons = ['pharmacy' => 'fa-pills text-warning', 'laboratory' => 'fa-microscope text-info', 'consultation' => 'fa-user-doctor text-primary', 'ward' => 'fa-bed text-success', 'theatre' => 'fa-scalpel text-danger'];
                        foreach($dept_revenue as $dept): 
                            $dName = strtolower($dept['department']);
                            $icon = $icons[$dName] ?? 'fa-building text-secondary';
                    ?>
                        <div class="dept-revenue-item">
                            <div class="d-flex align-items-center">
                                <div class="bg-light rounded-circle d-flex align-items-center justify-content-center border shadow-sm me-3" style="width: 40px; height: 40px;">
                                    <i class="fa-solid <?php echo $icon; ?>"></i>
                                </div>
                                <span class="fw-bold text-dark text-capitalize"><?php echo htmlspecialchars($dept['department']); ?></span>
                            </div>
                            <h5 class="m-0 fw-bold text-success">GHS <?php echo number_format($dept['gross_revenue'], 2); ?></h5>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // 1. Initialize Patient Search (Routes directly to universal billing interface)
    $('#patient_search').select2({
        placeholder: 'Enter Patient Name or ID...',
        ajax: {
            url: '/rimax/application/dripend/includes/account/api_search_patient.php', // Ensure this endpoint exists
            type: 'GET',
            dataType: 'json',
            delay: 250,
            data: function (params) { return { term: params.term }; },
            processResults: function (data) { return { results: data.results }; }
        }
    }).on('select2:select', function (e) {
        // Redirect to the new unified patient billing engine passing the patient ID
        window.location.href = 'patientBilling.php?patient_id=' + e.params.data.id;
    });

    // 2. Initialize Revenue Chart
    const ctx = document.getElementById('revenueChart').getContext('2d');
    const gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, 'rgba(2, 132, 199, 0.4)'); // Primary color fading out
    gradient.addColorStop(1, 'rgba(2, 132, 199, 0.0)');

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chart_labels); ?>,
            datasets: [{
                label: 'Gross Daily Collection (GHS)',
                data: <?php echo json_encode($chart_data); ?>,
                borderColor: '#0284c7',
                backgroundColor: gradient,
                borderWidth: 3,
                pointBackgroundColor: '#fff',
                pointBorderColor: '#0284c7',
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: '#1e293b',
                    padding: 12,
                    titleFont: { size: 13, family: 'Inter' },
                    bodyFont: { size: 14, family: 'Inter', weight: 'bold' },
                    displayColors: false,
                    callbacks: {
                        label: function(context) { return 'GHS ' + context.parsed.y.toFixed(2); }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: '#f1f5f9', drawBorder: false },
                    ticks: {
                        font: { family: 'Inter', weight: '600' }, color: '#64748b',
                        callback: function(value) { return 'GHS ' + value; }
                    }
                },
                x: {
                    grid: { display: false, drawBorder: false },
                    ticks: { font: { family: 'Inter', weight: '600' }, color: '#64748b' }
                }
            }
        }
    });
});
</script>
</body>
</html>