<?php
// filename: reconciliation.php (Fixed date filter for timestamp compatibility)
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', 'FINANCE_MANAGER'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Filters
$status_filter = $_GET['status'] ?? '';
$reconciler_filter = $_GET['reconciler'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$insurance_provider_filter = $_GET['insurance_provider'] ?? '';

// Build query for reconciliations - Fixed: Use DATE() for timestamp comparison
$recon_sql = "SELECT r.*, u.full_name as reconciler_name, ip.provider_name as insurance_provider_name,
                     (SELECT COUNT(*) FROM reconciliation_matches rm WHERE rm.reconciliation_id = r.reconciliation_id) as match_count,
                     (SELECT COUNT(*) FROM reconciliation_discrepancies rd WHERE rd.reconciliation_id = r.reconciliation_id) as discrepancy_count
              FROM reconciliations r
              LEFT JOIN users u ON r.reconciled_by = u.user_id
              LEFT JOIN insurance_providers ip ON r.insurance_provider_id = ip.provider_id
              WHERE 1=1";

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

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

if (!empty($reconciler_filter)) {
    $recon_sql .= " AND r.reconciled_by = ?";
    $params[] = $reconciler_filter;
    $types .= 'i';
}

if (!empty($insurance_provider_filter)) {
    $recon_sql .= " AND r.insurance_provider_id = ?";
    $params[] = $insurance_provider_filter;
    $types .= 'i';
}

// Fixed date filter: Cast timestamp to DATE for accurate matching
$recon_sql .= " AND DATE(r.reconciliation_date) BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';

$recon_sql .= " ORDER BY r.reconciliation_date DESC, r.reconciliation_id DESC LIMIT 100";

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

// Fetch users for reconciler filter - Corrected with JOIN to user_roles
$user_sql = "SELECT u.user_id, u.full_name
             FROM users u
             JOIN user_roles ur ON u.role_id = ur.role_id
             WHERE ur.role_code IN ('SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK', 'FINANCE_MANAGER')
             AND ur.is_active = 1
             AND u.status = 'ACTIVE'
             ORDER BY u.full_name";
$user_result = $conn->query($user_sql);

// Fetch insurance providers
$ip_sql = "SELECT provider_id, provider_name FROM insurance_providers ORDER BY provider_name";
$ip_result = $conn->query($ip_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Bill Reconciliations')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
   
    <style>
        .recon-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;
        }
       
        .recon-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
       
        .recon-entry {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
        }
       
        .recon-entry:hover {
            background: #f8fafc;
        }
       
        .recon-entry:last-child {
            border-bottom: none;
        }
       
        .recon-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-pending {
            background: #fef3c7;
            color: #92400e;
        }
       
        .status-completed {
            background: #d1fae5;
            color: #065f46;
        }
       
        .status-disputed {
            background: #fee2e2;
            color: #991b1b;
        }
       
        .provider-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            background: #e0e7ff;
            color: #3730a3;
        }
       
        .stats-display {
            font-weight: 700;
            font-size: 1.1rem;
            color: #1e293b;
        }
       
        .discrepancy-highlight {
            color: #dc2626;
        }
    </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">Bill Reconciliations</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">Reconciliations</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="recon-card">
                        <div class="recon-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="PENDING" <?php echo $status_filter === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                            <option value="COMPLETED" <?php echo $status_filter === 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                            <option value="DISPUTED" <?php echo $status_filter === 'DISPUTED' ? 'selected' : ''; ?>>Disputed</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Insurance Provider</label>
                                        <select class="form-select" name="insurance_provider">
                                            <option value="">All Providers</option>
                                            <?php $ip_result->data_seek(0); while ($ip = $ip_result->fetch_assoc()): ?>
                                            <option value="<?php echo $ip['provider_id']; ?>" <?php echo $insurance_provider_filter == $ip['provider_id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($ip['provider_name']); ?>
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">Reconciler</label>
                                        <select class="form-select" name="reconciler">
                                            <option value="">All Reconciler</option>
                                            <?php $user_result->data_seek(0); while ($user = $user_result->fetch_assoc()): ?>
                                            <option value="<?php echo $user['user_id']; ?>" <?php echo $reconciler_filter == $user['user_id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($user['full_name']); ?>
                                            </option>
                                            <?php endwhile; ?>
                                        </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>
                                <div class="row">
                                    <div class="col-md-12">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                        <a href="download_recon_template.php" class="btn btn-outline-success ms-2">
                                            <i class="ri-download-line me-1"></i>Download Template
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Reconciliations List -->
                    <div class="recon-card">
                        <div class="recon-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="ri-file-check-line me-2"></i>Reconciliation Runs</h5>
                                <a href="upload_reconciliation.php" class="btn btn-light btn-sm">
                                    <i class="ri-upload-line me-1"></i>Upload & Reconcile
                                </a>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <?php if ($recon_result->num_rows > 0): ?>
                                <?php while ($recon = $recon_result->fetch_assoc()): ?>
                                <div class="recon-entry">
                                    <div class="row align-items-center">
                                        <div class="col-md-2">
                                            <div class="recon-number"><?php echo htmlspecialchars($recon['reconciliation_number']); ?></div>
                                            <small class="text-muted"><?php echo date('d M Y', strtotime($recon['reconciliation_date'])); ?></small>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="fw-medium"><?php echo htmlspecialchars($recon['description']); ?></div>
                                            <div class="d-flex gap-2 mt-1">
                                                <?php if ($recon['insurance_provider_name']): ?>
                                                <span class="provider-badge">
                                                    <?php echo htmlspecialchars($recon['insurance_provider_name']); ?>
                                                </span>
                                                <?php endif; ?>
                                                <span class="badge bg-info">
                                                    <?php echo $recon['file_type']; ?> (<?php echo $recon['records_uploaded']; ?> records)
                                                </span>
                                            </div>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <span class="status-badge status-<?php echo strtolower($recon['status']); ?>">
                                                <?php echo $recon['status']; ?>
                                            </span>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <div class="stats-display">
                                                <?php echo $recon['match_count']; ?> matches
                                            </div>
                                            <?php if ($recon['discrepancy_count'] > 0): ?>
                                            <small class="text-muted discrepancy-highlight"><?php echo $recon['discrepancy_count']; ?> discrepancies</small>
                                            <?php else: ?>
                                            <small class="text-muted"><?php echo $recon['discrepancy_count']; ?> discrepancies</small>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-md-3 text-end">
                                            <div class="btn-group" role="group">
                                                <button class="btn btn-sm btn-outline-primary" onclick="viewReconciliation(<?php echo $recon['reconciliation_id']; ?>)">
                                                    <i class="ri-eye-line"></i> View
                                                </button>
                                                <a href="export_recon_report.php?id=<?php echo $recon['reconciliation_id']; ?>" class="btn btn-sm btn-outline-success">
                                                    <i class="ri-download-2-line"></i> Export
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="ri-file-search-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                    <p class="text-muted mt-2">No reconciliations found</p>
                                    <a href="upload_reconciliation.php" class="btn btn-primary mt-3">Start First Reconciliation</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Reconciliation Details Modal -->
    <div class="modal fade" id="reconciliationDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Reconciliation Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="reconciliationDetailsContent">
                    <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 viewReconciliation(reconId) {
        $('#reconciliationDetailsModal').modal('show');
       
        $.ajax({
            url: 'ajax/get_reconciliation_details.php',
            method: 'GET',
            data: { reconciliation_id: reconId },
            success: function(response) {
                $('#reconciliationDetailsContent').html(response);
            },
            error: function() {
                $('#reconciliationDetailsContent').html(
                    '<div class="alert alert-danger">Failed to load reconciliation details</div>'
                );
            }
        });
    }
    </script>
</body>
</html>