<?php
// billing_smart.php
session_start();
require_once('layouts/dbconn.php');
require_once('layouts/session.php');
require_once('layouts/smart_config.php');
require_once('layouts/header.php');

checkLogin($conn);

$patient_id = $_GET['patient_id'] ?? 0;
$visit_id = $_GET['visit_id'] ?? 0;

// Fetch patient and Smart session details
$patient_sql = "SELECT p.*, u.full_name, u.phone_primary, u.email,
                       pi.member_number, pi.insurance_number, pi.policy_number,
                       ic.company_name, ic.smart_enabled, ic.smart_medical_aid_code,
                       pv.visit_number, pv.visit_date,
                       ss.id as smart_session_id, ss.smart_session_id as smart_api_session_id,
                       ss.smart_patient_number, ss.smart_member_number,
                       ss.benefits_data, ss.session_status
                FROM patients p
                JOIN users u ON p.user_id = u.user_id
                LEFT JOIN patient_insurance pi ON p.patient_id = pi.patient_id
                LEFT JOIN insurance_companies ic ON pi.insurance_id = ic.insurance_id
                LEFT JOIN patient_visits pv ON p.patient_id = pv.patient_id AND pv.visit_id = ?
                LEFT JOIN smart_sessions ss ON pv.smart_session_id = ss.id
                WHERE p.patient_id = ?";

$stmt = $conn->prepare($patient_sql);
$stmt->bind_param("ii", $visit_id, $patient_id);
$stmt->execute();
$patient = $stmt->get_result()->fetch_assoc();

if (!$patient) {
    header('Location: list_patients.php');
    exit();
}

// Fetch Smart benefits
$benefits = [];
if ($patient['smart_session_id']) {
    $benefits_sql = "SELECT * FROM smart_benefits WHERE session_id = ? ORDER BY pool_number";
    $stmt = $conn->prepare($benefits_sql);
    $stmt->bind_param("i", $patient['smart_session_id']);
    $stmt->execute();
    $benefits = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

// Fetch available services
$services_sql = "SELECT s.*, sg.group_name, sg.group_code
                FROM services s
                JOIN service_groups sg ON s.group_id = sg.group_id
                WHERE s.is_active = 1
                ORDER BY sg.group_name, s.service_name";
$services = $conn->query($services_sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Smart Billing')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet">
    
    <style>
        .benefit-card {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .benefit-card:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .benefit-card.selected {
            border-color: #667eea;
            background: #eff6ff;
        }
        
        .benefit-amount {
            font-size: 1.5rem;
            font-weight: 700;
            color: #10b981;
        }
        
        .preauth-required {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .service-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .service-item:last-child {
            border-bottom: none;
        }
        
        .billing-summary {
            position: sticky;
            top: 20px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <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">
                                    <i class="ri-file-list-3-line me-2"></i>Smart Insurance Billing
                                </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"><a href="list_patients.php">Patients</a></li>
                                        <li class="breadcrumb-item active">Smart Billing</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left: Patient Info & Benefits -->
                        <div class="col-lg-8">
                            <!-- Patient Information Card -->
                            <div class="card">
                                <div class="card-header bg-gradient-primary text-white">
                                    <h5 class="mb-0">
                                        <i class="ri-user-line me-2"></i>Patient Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>Name:</strong> <?php echo htmlspecialchars($patient['full_name']); ?></p>
                                            <p><strong>Patient #:</strong> <?php echo htmlspecialchars($patient['patient_number']); ?></p>
                                            <p><strong>Visit #:</strong> <?php echo htmlspecialchars($patient['visit_number']); ?></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>Insurance:</strong> <?php echo htmlspecialchars($patient['company_name'] ?? 'N/A'); ?></p>
                                            <p><strong>Member #:</strong> <?php echo htmlspecialchars($patient['smart_member_number'] ?? 'N/A'); ?></p>
                                            <p><strong>Session Status:</strong> 
                                                <span class="badge bg-<?php echo $patient['session_status'] === 'ACTIVE' ? 'success' : 'warning'; ?>">
                                                    <?php echo $patient['session_status'] ?? 'N/A'; ?>
                                                </span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Available Benefits -->
                            <div class="card">
                                <div class="card-header bg-gradient-success text-white">
                                    <h5 class="mb-0">
                                        <i class="ri-shield-check-line me-2"></i>Available Benefits
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if (!empty($benefits)): ?>
                                        <div class="row">
                                            <?php foreach ($benefits as $benefit): ?>
                                                <div class="col-md-6">
                                                    <div class="benefit-card" data-benefit-id="<?php echo $benefit['id']; ?>" 
                                                         data-pool="<?php echo $benefit['pool_number']; ?>"
                                                         data-amount="<?php echo $benefit['amount']; ?>">
                                                        <h6><?php echo htmlspecialchars($benefit['pool_description']); ?></h6>
                                                        <div class="benefit-amount">
                                                            KES <?php echo number_format($benefit['amount'], 2); ?>
                                                        </div>
                                                        <small class="text-muted">Pool: <?php echo $benefit['pool_number']; ?></small>
                                                        <?php if ($benefit['claimable']): ?>
                                                            <span class="badge bg-success">Claimable</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-secondary">Not Claimable</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-warning">
                                            <i class="ri-alert-line me-2"></i>
                                            No Smart benefits available. Please ensure the Smart card has been forwarded and session is active.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Services Selection -->
                            <div class="card">
                                <div class="card-header bg-gradient-info text-white">
                                    <h5 class="mb-0">
                                        <i class="ri-shopping-cart-line me-2"></i>Add Services
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label class="form-label">Search Services</label>
                                        <select class="form-select select2" id="serviceSelect">
                                            <option value="">Select a service...</option>
                                            <?php 
                                            $current_group = '';
                                            while ($service = $services->fetch_assoc()):
                                                if ($current_group !== $service['group_name']) {
                                                    if ($current_group !== '') echo '</optgroup>';
                                                    echo '<optgroup label="' . htmlspecialchars($service['group_name']) . '">';
                                                    $current_group = $service['group_name'];
                                                }
                                            ?>
                                                <option value="<?php echo $service['service_id']; ?>"
                                                        data-name="<?php echo htmlspecialchars($service['service_name']); ?>"
                                                        data-code="<?php echo htmlspecialchars($service['service_code']); ?>"
                                                        data-price="<?php echo $service['service_price']; ?>"
                                                        data-group="<?php echo htmlspecialchars($service['group_code']); ?>">
                                                    <?php echo htmlspecialchars($service['service_name']); ?> 
                                                    (KES <?php echo number_format($service['service_price'], 2); ?>)
                                                </option>
                                            <?php 
                                            endwhile;
                                            if ($current_group !== '') echo '</optgroup>';
                                            ?>
                                        </select>
                                    </div>

                                    <!-- Selected Services List -->
                                    <div id="selectedServicesList">
                                        <h6>Selected Services</h6>
                                        <div id="servicesContainer">
                                            <p class="text-muted">No services selected yet</p>
                                        </div>
                                    </div>

                                    <button type="button" class="btn btn-primary mt-3" id="checkRulesBtn">
                                        <i class="ri-shield-check-line me-2"></i>Check Insurance Rules
                                    </button>
                                </div>
                            </div>

                            <!-- Pre-authorization Alert -->
                            <div id="preauthAlert" class="alert alert-warning preauth-required" style="display: none;">
                                <h6><i class="ri-alert-line me-2"></i>Pre-authorization Required</h6>
                                <p id="preauthMessage"></p>
                                <button type="button" class="btn btn-warning btn-sm" id="requestPreauthBtn">
                                    <i class="ri-file-list-line me-2"></i>Request Pre-authorization
                                </button>
                            </div>
                        </div>

                        <!-- Right: Billing Summary -->
                        <div class="col-lg-4">
                            <div class="billing-summary">
                                <div class="card">
                                    <div class="card-header bg-gradient-dark text-white">
                                        <h5 class="mb-0">
                                            <i class="ri-calculator-line me-2"></i>Billing Summary
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <strong>Selected Benefit Pool:</strong>
                                            <p id="selectedBenefitName" class="text-muted">Not selected</p>
                                        </div>

                                        <hr>

                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Subtotal:</span>
                                            <strong id="subtotalAmount">KES 0.00</strong>
                                        </div>

                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Copay:</span>
                                            <strong id="copayAmount" class="text-warning">KES 0.00</strong>
                                        </div>

                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Insurance Covers:</span>
                                            <strong id="insuranceAmount" class="text-success">KES 0.00</strong>
                                        </div>

                                        <hr>

                                        <div class="d-flex justify-content-between mb-3">
                                            <span><strong>Total:</strong></span>
                                            <strong id="totalAmount" class="text-primary" style="font-size: 1.5rem;">KES 0.00</strong>
                                        </div>

                                        <div class="d-flex justify-content-between mb-3">
                                            <span><strong>Patient Pays:</strong></span>
                                            <strong id="patientPaysAmount" class="text-danger" style="font-size: 1.25rem;">KES 0.00</strong>
                                        </div>

                                        <button type="button" class="btn btn-success w-100 btn-lg" id="submitBillBtn" disabled>
                                            <i class="ri-send-plane-fill me-2"></i>Submit to Smart & Generate Invoice
                                        </button>
                                    </div>
                                </div>

                                <!-- Copay Rules Display -->
                                <div class="card mt-3" id="copayRulesCard" style="display: none;">
                                    <div class="card-header bg-warning text-dark">
                                        <h6 class="mb-0">
                                            <i class="ri-information-line me-2"></i>Copay Rules
                                        </h6>
                                    </div>
                                    <div class="card-body" id="copayRulesContent">
                                    </div>
                                </div>