<?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', 'FINANCE_MANAGER', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get pre-authorization ID
$preauth_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$preauth_id) {
    header('Location: list_preauthorizations.php');
    exit();
}

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_status') {
        try {
            $conn->begin_transaction();
            
            $old_status_sql = "SELECT auth_status FROM insurance_pre_authorizations WHERE preauth_id = ?";
            $stmt = $conn->prepare($old_status_sql);
            $stmt->bind_param('i', $preauth_id);
            $stmt->execute();
            $old_status = $stmt->get_result()->fetch_assoc()['auth_status'];
            
            $update_sql = "UPDATE insurance_pre_authorizations SET 
                          auth_status = ?,
                          insurance_reference_number = ?,
                          insurance_notes = ?,
                          approved_amount = ?,
                          rejection_reason = ?,
                          approval_date = ?,
                          reviewed_by = ?
                          WHERE preauth_id = ?";
            
            $stmt = $conn->prepare($update_sql);
            $approval_date = in_array($_POST['new_status'], ['APPROVED', 'PARTIALLY_APPROVED', 'REJECTED']) ? date('Y-m-d H:i:s') : null;
            $approved_amount = isset($_POST['approved_amount']) && $_POST['approved_amount'] ? $_POST['approved_amount'] : null;
            
            $stmt->bind_param(
                'sssdssii',
                $_POST['new_status'],
                $_POST['insurance_reference'],
                $_POST['insurance_notes'],
                $approved_amount,
                $_POST['rejection_reason'],
                $approval_date,
                $_SESSION['user_id'],
                $preauth_id
            );
            $stmt->execute();
            
            // Log status change
            $history_sql = "INSERT INTO preauth_status_history (preauth_id, old_status, new_status, changed_by, change_reason, notes) 
                           VALUES (?, ?, ?, ?, ?, ?)";
            $hist_stmt = $conn->prepare($history_sql);
            $hist_stmt->bind_param(
                'ississ',
                $preauth_id,
                $old_status,
                $_POST['new_status'],
                $_SESSION['user_id'],
                $_POST['change_reason'],
                $_POST['status_notes']
            );
            $hist_stmt->execute();
            
            $conn->commit();
            $_SESSION['success_message'] = "Pre-authorization status updated successfully!";
            
        } catch (Exception $e) {
            $conn->rollback();
            $_SESSION['error_message'] = "Error updating status: " . $e->getMessage();
        }
        
        header("Location: view_preauthorization.php?id={$preauth_id}");
        exit();
    }
    
    if ($_POST['action'] === 'add_communication') {
        try {
            $comm_sql = "INSERT INTO preauth_communications 
                        (preauth_id, communication_type, direction, contact_person, contact_details, 
                         subject, message, outcome, follow_up_required, communicated_by, communication_date) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($comm_sql);
            $comm_date = date('Y-m-d H:i:s');
            
            $stmt->bind_param(
                'issssssssis',
                $preauth_id,
                $_POST['comm_type'],
                $_POST['direction'],
                $_POST['contact_person'],
                $_POST['contact_details'],
                $_POST['subject'],
                $_POST['message'],
                $_POST['outcome'],
                $_POST['follow_up_required'],
                $_SESSION['user_id'],
                $comm_date
            );
            $stmt->execute();
            
            $_SESSION['success_message'] = "Communication logged successfully!";
        } catch (Exception $e) {
            $_SESSION['error_message'] = "Error logging communication: " . $e->getMessage();
        }
        
        header("Location: view_preauthorization.php?id={$preauth_id}");
        exit();
    }
}

// Fetch pre-authorization details with FIXED column names
$preauth_sql = "SELECT 
                    pa.*,
                    p.patient_number, 
                    u.full_name as patient_name, 
                    u.phone_primary, 
                    u.email as patient_email,
                    u.national_id,
                    u.date_of_birth,
                    u.gender,
                    u.address as patient_address,
                    p.insurance_number,
                    p.policy_number,
                    p.employer,
                    ip.provider_name, 
                    ip.provider_code,
                    ip.contact_person as insurance_contact,
                    ip.phone as insurance_phone,
                    ip.email as insurance_email,
                    doc.full_name as doctor_name,
                    d.medical_license as doctor_license,
                    d.specialization,
                    doc.phone_primary as doctor_phone,
                    creator.full_name as created_by_name,
                    reviewer.full_name as reviewed_by_name,
                    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as patient_age,
                    DATEDIFF(pa.valid_until, CURDATE()) as days_until_expiry
                FROM insurance_pre_authorizations pa
                INNER JOIN patients p ON pa.patient_id = p.patient_id
                INNER JOIN users u ON p.user_id = u.user_id
                INNER JOIN insurance_providers ip ON pa.provider_id = ip.provider_id
                INNER JOIN users doc ON pa.requested_by = doc.user_id
                LEFT JOIN doctors d ON doc.user_id = d.user_id
                INNER JOIN users creator ON pa.created_by = creator.user_id
                LEFT JOIN users reviewer ON pa.reviewed_by = reviewer.user_id
                WHERE pa.preauth_id = ?";

$stmt = $conn->prepare($preauth_sql);
$stmt->bind_param('i', $preauth_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: list_preauthorizations.php');
    exit();
}

$preauth = $result->fetch_assoc();

// Fetch services
$services_sql = "SELECT * FROM preauth_services WHERE preauth_id = ? ORDER BY service_type";
$stmt = $conn->prepare($services_sql);
$stmt->bind_param('i', $preauth_id);
$stmt->execute();
$services = $stmt->get_result();

// Fetch communications
$comms_sql = "SELECT pc.*, u.full_name as communicated_by_name
              FROM preauth_communications pc
              INNER JOIN users u ON pc.communicated_by = u.user_id
              WHERE pc.preauth_id = ?
              ORDER BY pc.communication_date DESC";
$stmt = $conn->prepare($comms_sql);
$stmt->bind_param('i', $preauth_id);
$stmt->execute();
$communications = $stmt->get_result();

// Fetch status history
$history_sql = "SELECT psh.*, u.full_name as changed_by_name
                FROM preauth_status_history psh
                INNER JOIN users u ON psh.changed_by = u.user_id
                WHERE psh.preauth_id = ?
                ORDER BY psh.changed_at DESC";
$stmt = $conn->prepare($history_sql);
$stmt->bind_param('i', $preauth_id);
$stmt->execute();
$status_history = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pre-Authorization Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .detail-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .preauth-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
        }
        
        .info-item {
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-item:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-size: 0.875rem;
            color: #64748b;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-size: 1rem;
            color: #1e293b;
            font-weight: 500;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-draft { background: #e0e7ff; color: #3730a3; }
        .status-submitted { background: #dbeafe; color: #1e40af; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-under_review { background: #fed7aa; color: #9a3412; }
        .status-approved { background: #d1fae5; color: #065f46; }
        .status-partially_approved { background: #a7f3d0; color: #064e3b; }
        .status-rejected { background: #fee2e2; color: #991b1b; }
        .status-expired { background: #f3f4f6; color: #4b5563; }
        .status-cancelled { background: #e5e7eb; color: #374151; }
        
        .urgency-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .urgency-routine { background: #e0f2fe; color: #075985; }
        .urgency-urgent { background: #fed7aa; color: #9a3412; }
        .urgency-emergency { background: #fee2e2; color: #991b1b; }
        
        .timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .timeline::before {
            content: '';
            position: absolute;
            left: 0.5rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -1.5rem;
            top: 0.25rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #3b82f6;
            border: 3px solid white;
            box-shadow: 0 0 0 2px #e2e8f0;
        }
        
        .timeline-item:last-child {
            padding-bottom: 0;
        }
        
        .communication-item {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            border-left: 4px solid #3b82f6;
            margin-bottom: 1rem;
        }
        
        .communication-item.outbound {
            border-left-color: #10b981;
        }
        
        .communication-item.inbound {
            border-left-color: #f59e0b;
        }
        
        .service-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .service-table th {
            background: #f8fafc;
            padding: 0.75rem;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .service-table td {
            padding: 0.75rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .service-table tr:last-child td {
            border-bottom: none;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .alert-box {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .alert-warning {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            color: #92400e;
        }
        
        .alert-danger {
            background: #fee2e2;
            border-left: 4px solid #dc2626;
            color: #991b1b;
        }
        
        .alert-success {
            background: #d1fae5;
            border-left: 4px solid #10b981;
            color: #065f46;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .amount-highlight {
            background: #f0fdf4;
            padding: 1rem;
            border-radius: 8px;
            border: 2px solid #86efac;
            text-align: center;
        }
        
        .amount-highlight .amount {
            font-size: 1.75rem;
            font-weight: 700;
            color: #166534;
        }
    </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 Title -->
                    <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">Pre-Authorization Details</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_preauthorizations.php">Pre-Authorizations</a></li>
                                        <li class="breadcrumb-item active">View Details</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Header with Status -->
                    <div class="preauth-header">
                        <div class="row align-items-center">
                            <div class="col-lg-8">
                                <h3 class="mb-2">Pre-Authorization #<?php echo htmlspecialchars($preauth['preauth_number']); ?></h3>
                                <p class="mb-2">
                                    <i class="ri-user-line me-1"></i> <?php echo htmlspecialchars($preauth['patient_name']); ?> 
                                    <span class="mx-2">|</span>
                                    <i class="ri-calendar-line me-1"></i> <?php echo date('d M Y', strtotime($preauth['request_date'])); ?>
                                </p>
                                <div class="d-flex gap-2 align-items-center">
                                    <span class="status-badge status-<?php echo strtolower($preauth['auth_status']); ?>">
                                        <?php echo str_replace('_', ' ', $preauth['auth_status']); ?>
                                    </span>
                                    <span class="urgency-badge urgency-<?php echo strtolower($preauth['urgency_level']); ?>">
                                        <?php echo $preauth['urgency_level']; ?>
                                    </span>
                                </div>
                            </div>
                            <div class="col-lg-4 text-lg-end mt-3 mt-lg-0">
                                <div class="amount-highlight" style="background: rgba(255,255,255,0.2); border-color: rgba(255,255,255,0.3);">
                                    <div style="font-size: 0.875rem; color: rgba(255,255,255,0.8); margin-bottom: 0.25rem;">Requested Amount</div>
                                    <div class="amount" style="color: white;">KES <?php echo number_format($preauth['requested_amount'], 2); ?></div>
                                    <?php if ($preauth['approved_amount']): ?>
                                    <div style="font-size: 0.875rem; color: rgba(255,255,255,0.8); margin-top: 0.5rem;">
                                        Approved: KES <?php echo number_format($preauth['approved_amount'], 2); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="detail-card">
                        <div class="action-buttons">
                            <a href="letter_of_undertaking.php?id=<?php echo $preauth_id; ?>" class="btn btn-primary" target="_blank">
                                <i class="ri-file-text-line me-1"></i> Generate Letter
                            </a>
                            <a href="letter_of_undertaking.php?id=<?php echo $preauth_id; ?>&auto_print=true" class="btn btn-info" target="_blank">
                                <i class="ri-printer-line me-1"></i> Print Letter
                            </a>
                            <?php if (in_array($preauth['auth_status'], ['DRAFT', 'SUBMITTED', 'PENDING'])): ?>
                            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#updateStatusModal">
                                <i class="ri-refresh-line me-1"></i> Update Status
                            </button>
                            <?php endif; ?>
                            <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#addCommunicationModal">
                                <i class="ri-message-3-line me-1"></i> Log Communication
                            </button>
                            <a href="patient_profile.php?id=<?php echo $preauth['patient_id']; ?>" class="btn btn-outline-primary">
                                <i class="ri-user-line me-1"></i> View Patient
                            </a>
                            <a href="list_preauthorizations.php" class="btn btn-outline-secondary">
                                <i class="ri-arrow-left-line me-1"></i> Back to List
                            </a>
                        </div>
                    </div>

                    <!-- Alerts -->
                    <?php if ($preauth['auth_status'] === 'EXPIRED' || ($preauth['days_until_expiry'] < 0 && $preauth['valid_until'])): ?>
                    <div class="alert-box alert-danger">
                        <i class="ri-error-warning-line me-2"></i>
                        <strong>Expired:</strong> This pre-authorization expired on <?php echo date('d M Y', strtotime($preauth['valid_until'])); ?>
                    </div>
                    <?php elseif ($preauth['days_until_expiry'] <= 7 && $preauth['days_until_expiry'] > 0): ?>
                    <div class="alert-box alert-warning">
                        <i class="ri-alarm-warning-line me-2"></i>
                        <strong>Expiring Soon:</strong> This pre-authorization will expire in <?php echo $preauth['days_until_expiry']; ?> days
                    </div>
                    <?php endif; ?>

                    <?php if ($preauth['auth_status'] === 'APPROVED'): ?>
                    <div class="alert-box alert-success">
                        <i class="ri-check-line me-2"></i>
                        <strong>Approved:</strong> This pre-authorization was approved on <?php echo date('d M Y H:i', strtotime($preauth['approval_date'])); ?>
                        <?php if ($preauth['insurance_reference_number']): ?>
                        | Reference: <?php echo htmlspecialchars($preauth['insurance_reference_number']); ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-8">
                            <!-- Patient Information -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-user-line"></i> Patient Information
                                </div>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <div class="info-label">Full Name</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['patient_name']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Patient Number</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['patient_number']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">National ID</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['national_id']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Date of Birth / Age</div>
                                        <div class="info-value">
                                            <?php echo date('d M Y', strtotime($preauth['date_of_birth'])); ?> 
                                            (<?php echo $preauth['patient_age']; ?> years)
                                        </div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Gender</div>
                                        <div class="info-value"><?php echo ucfirst(strtolower($preauth['gender'])); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Contact Phone</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['phone_primary']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Email</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['patient_email'] ?: 'Not provided'); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Address</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['patient_address'] ?: 'Not provided'); ?></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Insurance Information -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-shield-check-line"></i> Insurance Information
                                </div>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <div class="info-label">Insurance Provider</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['provider_name']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Provider Code</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['provider_code']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Member/Insurance Number</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['insurance_number']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Policy Number</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['policy_number']); ?></div>
                                    </div>
                                    <?php if ($preauth['employer']): ?>
                                    <div class="info-item">
                                        <div class="info-label">Employer</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['employer']); ?></div>
                                    </div>
                                    <?php endif; ?>
                                    <div class="info-item">
                                        <div class="info-label">Insurance Contact Person</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['insurance_contact'] ?: 'Not specified'); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Insurance Phone</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['insurance_phone']); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Insurance Email</div>
                                        <div class="info-value"><?php echo htmlspecialchars($preauth['insurance_email']); ?></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Medical Information -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-heart-pulse-line"></i> Medical Information
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <div class="info-item">
                                            <div class="info-label">Service Type</div>
                                            <div class="info-value"><?php echo ucfirst(str_replace('_', ' ', strtolower($preauth['service_type']))); ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="info-item">
                                            <div class="info-label">Service Category</div>
                                            <div class="info-value"><?php echo htmlspecialchars($preauth['service_category'] ?: 'Not specified'); ?></div>
                                        </div>
                                    </div>
                                </div>

                                <?php if ($preauth['diagnosis_code']): ?>
                                <div class="info-item">
                                    <div class="info-label">ICD-10 Diagnosis Code</div>
                                    <div class="info-value"><strong><?php echo htmlspecialchars($preauth['diagnosis_code']); ?></strong></div>
                                </div>
                                <?php endif; ?>

                                <div class="info-item">
                                    <div class="info-label">Diagnosis Description</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($preauth['diagnosis_description'])); ?></div>
                                </div>

                                <div class="info-item">
                                    <div class="info-label">Clinical Indication / Medical Necessity</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($preauth['clinical_indication'])); ?></div>
                                </div>

                                <div class="info-item">
                                    <div class="info-label">Treatment Plan</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($preauth['treatment_plan'])); ?></div>
                                </div>

                                <?php if ($preauth['estimated_duration']): ?>
                                <div class="info-item">
                                    <div class="info-label">Estimated Duration</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['estimated_duration']); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Services/Procedures -->
                            <?php if ($services->num_rows > 0): ?>
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-service-line"></i> Services/Procedures Requested
                                </div>
                                <div class="table-responsive">
                                    <table class="service-table">
                                        <thead>
                                            <tr>
                                                <th>Service Type</th>
                                                <th>Service Name</th>
                                                <th>Description</th>
                                                <th style="text-align: right;">Qty</th>
                                                <th style="text-align: right;">Unit Cost</th>
                                                <th style="text-align: right;">Total</th>
                                                <?php if ($preauth['auth_status'] === 'APPROVED' || $preauth['auth_status'] === 'PARTIALLY_APPROVED'): ?>
                                                <th style="text-align: right;">Approved</th>
                                                <?php endif; ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $total_cost = 0;
                                            $total_approved = 0;
                                            while ($service = $services->fetch_assoc()): 
                                                $total_cost += $service['total_cost'];
                                                if ($service['approved_amount']) {
                                                    $total_approved += $service['approved_amount'];
                                                }
                                            ?>
                                            <tr>
                                                <td><?php echo ucfirst(str_replace('_', ' ', strtolower($service['service_type']))); ?></td>
                                                <td><strong><?php echo htmlspecialchars($service['service_name']); ?></strong></td>
                                                <td><?php echo htmlspecialchars($service['service_description'] ?: '-'); ?></td>
                                                <td style="text-align: right;"><?php echo $service['quantity']; ?></td>
                                                <td style="text-align: right;">KES <?php echo number_format($service['unit_cost'], 2); ?></td>
                                                <td style="text-align: right;"><strong>KES <?php echo number_format($service['total_cost'], 2); ?></strong></td>
                                                <?php if ($preauth['auth_status'] === 'APPROVED' || $preauth['auth_status'] === 'PARTIALLY_APPROVED'): ?>
                                                <td style="text-align: right;">
                                                    <?php if ($service['approved_amount']): ?>
                                                    <strong class="text-success">KES <?php echo number_format($service['approved_amount'], 2); ?></strong>
                                                    <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <?php endif; ?>
                                            </tr>
                                            <?php endwhile; ?>
                                            <tr style="background: #f8fafc; font-weight: 600;">
                                                <td colspan="5" style="text-align: right;">TOTAL:</td>
                                                <td style="text-align: right;">KES <?php echo number_format($total_cost, 2); ?></td>
                                                <?php if ($preauth['auth_status'] === 'APPROVED' || $preauth['auth_status'] === 'PARTIALLY_APPROVED'): ?>
                                                <td style="text-align: right;" class="text-success">KES <?php echo number_format($total_approved, 2); ?></td>
                                                <?php endif; ?>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Communication Log -->
                            <?php if ($communications->num_rows > 0): ?>
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-message-3-line"></i> Communication Log
                                </div>
                                <?php while ($comm = $communications->fetch_assoc()): ?>
                                <div class="communication-item <?php echo strtolower($comm['direction']); ?>">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div>
                                            <strong><?php echo ucfirst(strtolower($comm['communication_type'])); ?></strong>
                                            <span class="badge bg-<?php echo $comm['direction'] === 'OUTBOUND' ? 'success' : 'warning'; ?> ms-2">
                                                <?php echo $comm['direction']; ?>
                                            </span>
                                        </div>
                                        <small class="text-muted">
                                            <?php echo date('d M Y, H:i', strtotime($comm['communication_date'])); ?>
                                        </small>
                                    </div>
                                    <?php if ($comm['subject']): ?>
                                    <div class="mb-1"><strong>Subject:</strong> <?php echo htmlspecialchars($comm['subject']); ?></div>
                                    <?php endif; ?>
                                    <?php if ($comm['contact_person']): ?>
                                    <div class="mb-1"><strong>Contact:</strong> <?php echo htmlspecialchars($comm['contact_person']); ?> 
                                        <?php if ($comm['contact_details']): ?>
                                        (<?php echo htmlspecialchars($comm['contact_details']); ?>)
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($comm['message']): ?>
                                    <div class="mb-1"><?php echo nl2br(htmlspecialchars($comm['message'])); ?></div>
                                    <?php endif; ?>
                                    <?php if ($comm['outcome']): ?>
                                    <div class="mb-1"><strong>Outcome:</strong> <?php echo htmlspecialchars($comm['outcome']); ?></div>
                                    <?php endif; ?>
                                    <?php if ($comm['follow_up_required']): ?>
                                    <div class="mt-2">
                                        <span class="badge bg-warning">Follow-up Required</span>
                                    </div>
                                    <?php endif; ?>
                                    <div class="mt-2 text-muted" style="font-size: 0.875rem;">
                                        <i class="ri-user-line"></i> Logged by: <?php echo htmlspecialchars($comm['communicated_by_name']); ?>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Status History -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-history-line"></i> Status History
                                </div>
                                <div class="timeline">
                                    <?php while ($history = $status_history->fetch_assoc()): ?>
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-start mb-1">
                                            <div>
                                                <strong>
                                                    <?php if ($history['old_status']): ?>
                                                    <?php echo str_replace('_', ' ', $history['old_status']); ?> → 
                                                    <?php endif; ?>
                                                    <?php echo str_replace('_', ' ', $history['new_status']); ?>
                                                </strong>
                                            </div>
                                            <small class="text-muted">
                                                <?php echo date('d M Y, H:i', strtotime($history['changed_at'])); ?>
                                            </small>
                                        </div>
                                        <?php if ($history['change_reason']): ?>
                                        <div class="text-muted mb-1"><?php echo htmlspecialchars($history['change_reason']); ?></div>
                                        <?php endif; ?>
                                        <?php if ($history['notes']): ?>
                                        <div class="mb-1"><?php echo nl2br(htmlspecialchars($history['notes'])); ?></div>
                                        <?php endif; ?>
                                        <small class="text-muted">
                                            <i class="ri-user-line"></i> <?php echo htmlspecialchars($history['changed_by_name']); ?>
                                        </small>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-4">
                            <!-- Authorization Summary -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-information-line"></i> Authorization Summary
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Pre-Auth Number</div>
                                    <div class="info-value"><strong><?php echo htmlspecialchars($preauth['preauth_number']); ?></strong></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Status</div>
                                    <div class="info-value">
                                        <span class="status-badge status-<?php echo strtolower($preauth['auth_status']); ?>">
                                            <?php echo str_replace('_', ' ', $preauth['auth_status']); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Priority</div>
                                    <div class="info-value">
                                        <span class="badge bg-<?php echo $preauth['priority_status'] === 'URGENT' ? 'danger' : ($preauth['priority_status'] === 'PRIORITY' ? 'warning' : 'secondary'); ?>">
                                            <?php echo $preauth['priority_status']; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Urgency Level</div>
                                    <div class="info-value">
                                        <span class="urgency-badge urgency-<?php echo strtolower($preauth['urgency_level']); ?>">
                                            <?php echo $preauth['urgency_level']; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Request Date</div>
                                    <div class="info-value"><?php echo date('d M Y', strtotime($preauth['request_date'])); ?></div>
                                </div>
                                <?php if ($preauth['submission_date']): ?>
                                <div class="info-item">
                                    <div class="info-label">Submission Date</div>
                                    <div class="info-value"><?php echo date('d M Y H:i', strtotime($preauth['submission_date'])); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['valid_from']): ?>
                                <div class="info-item">
                                    <div class="info-label">Valid From</div>
                                    <div class="info-value"><?php echo date('d M Y', strtotime($preauth['valid_from'])); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['valid_until']): ?>
                                <div class="info-item">
                                    <div class="info-label">Valid Until</div>
                                    <div class="info-value">
                                        <?php echo date('d M Y', strtotime($preauth['valid_until'])); ?>
                                        <?php if ($preauth['days_until_expiry'] < 0): ?>
                                        <span class="badge bg-danger ms-2">Expired</span>
                                        <?php elseif ($preauth['days_until_expiry'] <= 7): ?>
                                        <span class="badge bg-warning ms-2"><?php echo $preauth['days_until_expiry']; ?> days left</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['approval_date']): ?>
                                <div class="info-item">
                                    <div class="info-label">Approval/Decision Date</div>
                                    <div class="info-value"><?php echo date('d M Y H:i', strtotime($preauth['approval_date'])); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['insurance_reference_number']): ?>
                                <div class="info-item">
                                    <div class="info-label">Insurance Reference</div>
                                    <div class="info-value"><strong><?php echo htmlspecialchars($preauth['insurance_reference_number']); ?></strong></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Financial Summary -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-money-dollar-circle-line"></i> Financial Summary
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Estimated Cost</div>
                                    <div class="info-value">KES <?php echo number_format($preauth['estimated_cost'], 2); ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Requested Amount</div>
                                    <div class="info-value"><strong>KES <?php echo number_format($preauth['requested_amount'], 2); ?></strong></div>
                                </div>
                                <?php if ($preauth['approved_amount']): ?>
                                <div class="info-item">
                                    <div class="info-label">Approved Amount</div>
                                    <div class="info-value text-success"><strong>KES <?php echo number_format($preauth['approved_amount'], 2); ?></strong></div>
                                </div>
                                <?php 
                                $approval_percentage = ($preauth['approved_amount'] / $preauth['requested_amount']) * 100;
                                ?>
                                <div class="info-item">
                                    <div class="info-label">Approval Rate</div>
                                    <div class="info-value">
                                        <span class="badge bg-<?php echo $approval_percentage >= 90 ? 'success' : ($approval_percentage >= 70 ? 'warning' : 'danger'); ?>">
                                            <?php echo number_format($approval_percentage, 1); ?>%
                                        </span>
                                    </div>
                                </div>
                                <?php endif; ?>
                                <div class="info-item">
                                    <div class="info-label">Patient Co-pay</div>
                                    <div class="info-value">KES <?php echo number_format($preauth['patient_copay'], 2); ?></div>
                                </div>
                            </div>

                            <!-- Doctor Information -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-stethoscope-line"></i> Requesting Doctor
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Name</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['doctor_name']); ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Specialization</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['specialization']); ?></div>
                                </div>
                                <?php if ($preauth['doctor_license']): ?>
                                <div class="info-item">
                                    <div class="info-label">Medical License Number</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['doctor_license']); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['doctor_phone']): ?>
                                <div class="info-item">
                                    <div class="info-label">Contact</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['doctor_phone']); ?></div>
                                </div>
                                <?php endif; ?>
                                <div class="info-item">
                                    <div class="info-label">Department</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['requesting_department']); ?></div>
                                </div>
                            </div>

                            <!-- Additional Information -->
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-file-info-line"></i> Additional Information
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Created By</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['created_by_name']); ?></div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Created Date</div>
                                    <div class="info-value"><?php echo date('d M Y H:i', strtotime($preauth['created_at'])); ?></div>
                                </div>
                                <?php if ($preauth['reviewed_by_name']): ?>
                                <div class="info-item">
                                    <div class="info-label">Reviewed By</div>
                                    <div class="info-value"><?php echo htmlspecialchars($preauth['reviewed_by_name']); ?></div>
                                </div>
                                <?php endif; ?>
                                <div class="info-item">
                                    <div class="info-label">Last Updated</div>
                                    <div class="info-value"><?php echo date('d M Y H:i', strtotime($preauth['updated_at'])); ?></div>
                                </div>
                                <?php if ($preauth['follow_up_required']): ?>
                                <div class="info-item">
                                    <div class="info-label">Follow-up Status</div>
                                    <div class="info-value">
                                        <span class="badge bg-warning">Follow-up Required</span>
                                        <?php if ($preauth['follow_up_date']): ?>
                                        <br><small>Due: <?php echo date('d M Y', strtotime($preauth['follow_up_date'])); ?></small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Insurance Notes -->
                            <?php if ($preauth['insurance_notes'] || $preauth['rejection_reason'] || $preauth['conditions_limitations']): ?>
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-file-list-3-line"></i> Insurance Response
                                </div>
                                <?php if ($preauth['insurance_notes']): ?>
                                <div class="info-item">
                                    <div class="info-label">Insurance Notes</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($preauth['insurance_notes'])); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['rejection_reason']): ?>
                                <div class="info-item">
                                    <div class="info-label">Rejection Reason</div>
                                    <div class="info-value text-danger"><?php echo nl2br(htmlspecialchars($preauth['rejection_reason'])); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($preauth['conditions_limitations']): ?>
                                <div class="info-item">
                                    <div class="info-label">Conditions & Limitations</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($preauth['conditions_limitations'])); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Internal Notes -->
                            <?php if ($preauth['internal_notes']): ?>
                            <div class="detail-card">
                                <div class="section-title">
                                    <i class="ri-sticky-note-line"></i> Internal Notes
                                </div>
                                <div class="info-value"><?php echo nl2br(htmlspecialchars($preauth['internal_notes'])); ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Update Status Modal -->
    <div class="modal fade" id="updateStatusModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Update Authorization Status</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="">
                    <input type="hidden" name="action" value="update_status">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">New Status <span class="text-danger">*</span></label>
                                <select class="form-select" name="new_status" id="newStatus" required>
                                    <option value="SUBMITTED">Submitted</option>
                                    <option value="PENDING">Pending</option>
                                    <option value="UNDER_REVIEW">Under Review</option>
                                    <option value="APPROVED">Approved</option>
                                    <option value="PARTIALLY_APPROVED">Partially Approved</option>
                                    <option value="REJECTED">Rejected</option>
                                    <option value="CANCELLED">Cancelled</option>
                                    <option value="EXPIRED">Expired</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Insurance Reference Number</label>
                                <input type="text" class="form-control" name="insurance_reference" 
                                       value="<?php echo htmlspecialchars($preauth['insurance_reference_number'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="mb-3" id="approvedAmountDiv" style="display: none;">
                            <label class="form-label">Approved Amount (KES)</label>
                            <input type="number" step="0.01" class="form-control" name="approved_amount" 
                                   value="<?php echo $preauth['approved_amount'] ?? ''; ?>">
                        </div>

                        <div class="mb-3" id="rejectionReasonDiv" style="display: none;">
                            <label class="form-label">Rejection Reason</label>
                            <textarea class="form-control" name="rejection_reason" rows="3"><?php echo htmlspecialchars($preauth['rejection_reason'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Change Reason <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="change_reason" required 
                                   placeholder="Brief reason for this status change">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Insurance Notes</label>
                            <textarea class="form-control" name="insurance_notes" rows="3" 
                                      placeholder="Notes from insurance company"><?php echo htmlspecialchars($preauth['insurance_notes'] ?? ''); ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Additional Notes</label>
                            <textarea class="form-control" name="status_notes" rows="2" 
                                      placeholder="Additional notes about this status change"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Status</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Communication Modal -->
    <div class="modal fade" id="addCommunicationModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Log Communication</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="">
                    <input type="hidden" name="action" value="add_communication">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Communication Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="comm_type" required>
                                    <option value="PHONE">Phone Call</option>
                                    <option value="EMAIL">Email</option>
                                    <option value="FAX">Fax</option>
                                    <option value="PORTAL">Online Portal</option>
                                    <option value="IN_PERSON">In Person</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Direction <span class="text-danger">*</span></label>
                                <select class="form-select" name="direction" required>
                                    <option value="OUTBOUND">Outbound (We contacted them)</option>
                                    <option value="INBOUND">Inbound (They contacted us)</option>
                                </select>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Contact Person</label>
                                <input type="text" class="form-control" name="contact_person" 
                                       placeholder="Name of person contacted">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Contact Details</label>
                                <input type="text" class="form-control" name="contact_details" 
                                       placeholder="Phone/Email">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Subject</label>
                            <input type="text" class="form-control" name="subject" 
                                   placeholder="Brief subject of communication">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Message/Notes <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="message" rows="4" required 
                                      placeholder="Details of the communication"></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Outcome</label>
                            <input type="text" class="form-control" name="outcome" 
                                   placeholder="What was the outcome or next step?">
                        </div>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="follow_up_required" value="1" id="followUpCheck">
                            <label class="form-check-label" for="followUpCheck">
                                Follow-up Required
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Communication</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Show/hide fields based on status selection
            $('#newStatus').on('change', function() {
                const status = $(this).val();
                
                if (status === 'APPROVED' || status === 'PARTIALLY_APPROVED') {
                    $('#approvedAmountDiv').show();
                    $('#rejectionReasonDiv').hide();
                } else if (status === 'REJECTED') {
                    $('#rejectionReasonDiv').show();
                    $('#approvedAmountDiv').hide();
                } else {
                    $('#approvedAmountDiv').hide();
                    $('#rejectionReasonDiv').hide();
                }
            });

            // Display success/error messages
            <?php if (isset($_SESSION['success_message'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo $_SESSION['success_message']; ?>',
                timer: 3000
            });
            <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['error_message'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: '<?php echo $_SESSION['error_message']; ?>',
                timer: 3000
            });
            <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>