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

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

$code = $_GET['code'] ?? '';
$pre_auth = null;

if ($code) {
    $sql = "SELECT 
        pa.*,
        m.surname,
        m.first_name,
        m.other_names,
        c.corporate,
        p.provider_name,
        mb.limit as benefit_limit,
        mb.category
    FROM pre_authorization pa
    LEFT JOIN member_info m ON pa.member_no = m.member_no
    LEFT JOIN corporate c ON m.corp_id = c.corp_id
    LEFT JOIN providers p ON pa.provider = p.provider_id
    LEFT JOIN member_benefits mb ON m.member_no = mb.member_no
    WHERE pa.code = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $code);
    $stmt->execute();
    $pre_auth = $stmt->get_result()->fetch_assoc();
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Pre-Authorization')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .status-badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-pending { background-color: #fff3cd; color: #856404; }
        .status-approved { background-color: #d4edda; color: #155724; }
        .status-rejected { background-color: #f8d7da; color: #721c24; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Pre-Authorization', 'title' => 'View Pre-Authorization')); ?>

                    <?php if (!$pre_auth): ?>
                        <div class="alert alert-danger">
                            <i class="ri-error-warning-line me-2"></i>
                            Pre-authorization not found or has been deleted.
                        </div>
                    <?php else: ?>
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header bg-soft-primary">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title flex-grow-1 mb-0">
                                            Pre-Authorization #<?php echo htmlspecialchars($pre_auth['pre_auth_code']); ?>
                                        </h5>
                                        <div class="flex-shrink-0">
                                            <div class="d-flex gap-2">
                                                <button type="button" id="backBtn" class="btn btn-secondary btn-sm">
                                                    <i class="ri-arrow-left-line align-middle me-1"></i> Back to Pre Auth List
                                                </button>
                                                
                                                <button type="button" id="printBtn" class="btn btn-info btn-sm">
                                                    <i class="ri-printer-line align-middle me-1"></i> Print
                                                </button>
                                                <?php if ($_SESSION['user_role'] === 'admin'): ?>
                                                <button type="button" class="btn btn-primary btn-sm" 
                                                        onclick="editPreAuth(<?php echo $code; ?>)">
                                                    <i class="ri-edit-2-line align-middle me-1"></i> Edit
                                                </button>
                                                <?php endif; ?>
                                                <button type="button" class="btn btn-primary" onclick="createClaimFromPreAuth(<?php echo $pre_auth['code']; ?>)">
                                                    <i class="ri-file-add-line align-middle me-1"></i> Create Claim
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="row g-3">
                                        <!-- Basic Information -->
                                        <div class="col-lg-12">
                                            <div class="card border shadow-none mb-4">
                                                <div class="card-header">
                                                    <h6 class="card-title mb-0">Basic Information</h6>
                                                </div>
                                                <div class="card-body">
                                                    <div class="row">
                                                        <div class="col-lg-6">
                                                            <dl class="row mb-0">
                                                                <dt class="col-sm-4">Member Name:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['surname'] . ' ' . 
                                                                        $pre_auth['first_name'] . ' ' . 
                                                                        $pre_auth['other_names']); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Member Number:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['member_no']); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Corporate:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['corporate']); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Benefit Category:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['category']); ?>
                                                                </dd>
                                                            </dl>
                                                        </div>
                                                        <div class="col-lg-6">
                                                            <dl class="row mb-0">
                                                                <dt class="col-sm-4">Provider:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['provider_name']); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Date Created:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo date('d M Y', strtotime($pre_auth['date_entered'])); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Reported By:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['reported_by']); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Date Reported:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo date('d M Y', strtotime($pre_auth['date_reported'])); ?>
                                                                </dd>
                                                            </dl>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Authorization Details -->
                                        <div class="col-lg-12">
                                            <div class="card border shadow-none">
                                                <div class="card-header">
                                                    <h6 class="card-title mb-0">Authorization Details</h6>
                                                </div>
                                                <div class="card-body">
                                                    <div class="row">
                                                        <div class="col-lg-6">
                                                            <dl class="row mb-0">
                                                                <dt class="col-sm-4">Authority Type:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php
                                                                    $auth_types = [
                                                                        1 => 'Inpatient',
                                                                        2 => 'Outpatient',
                                                                        3 => 'Day Care'
                                                                    ];
                                                                    echo $auth_types[$pre_auth['authority_type']] ?? 'N/A';
                                                                    ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Ward Type:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php
                                                                    $wards = [
                                                                        1 => 'General Ward',
                                                                        2 => 'Private Room',
                                                                        3 => 'ICU'
                                                                    ];
                                                                    echo $wards[$pre_auth['ward']] ?? 'N/A';
                                                                    ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Admission Days:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo $pre_auth['admit_days'] ?: 'N/A'; ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Attending Doctor:</dt>
                                                                <dd class="col-sm-8">
                                                                    <?php echo htmlspecialchars($pre_auth['doctor_attending']) ?: 'N/A'; ?>
                                                                </dd>
                                                            </dl>
                                                        </div>
                                                        <div class="col-lg-6">
                                                            <dl class="row mb-0">
                                                                <dt class="col-sm-4">Available Limit:</dt>
                                                                <dd class="col-sm-8">
                                                                    Ksh <?php echo number_format($pre_auth['available_limit'], 2); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Reserved Amount:</dt>
                                                                <dd class="col-sm-8">
                                                                    Ksh <?php echo number_format($pre_auth['reserve'], 2); ?>
                                                                </dd>

                                                                <dt class="col-sm-4">Balance:</dt>
                                                                <dd class="col-sm-8">
                                                                    Ksh <?php echo number_format($pre_auth['available_limit'] - $pre_auth['reserve'], 2); ?>
                                                                </dd>
                                                            </dl>
                                                        </div>
                                                    </div>

                                                    <div class="row mt-4">
                                                        <div class="col-lg-12">
                                                            <h6 class="mb-3">Pre-Diagnosis:</h6>
                                                            <div class="alert alert-info mb-0">
                                                                <?php echo nl2br(htmlspecialchars($pre_auth['pre_diagnosis'])); ?>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <?php if ($pre_auth['notes']): ?>
                                                    <div class="row mt-4">
                                                        <div class="col-lg-12">
                                                            <h6 class="mb-3">Additional Notes:</h6>
                                                            <div class="alert alert-secondary mb-0">
                                                                <?php echo nl2br(htmlspecialchars($pre_auth['notes'])); ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Activity Log -->
                                        <div class="col-lg-12">
                                            <div class="card border shadow-none">
                                                <div class="card-header">
                                                    <h6 class="card-title mb-0">Activity History</h6>
                                                </div>
                                                <div class="card-body">
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered align-middle table-nowrap mb-0">
                                                            <thead class="table-light">
                                                                <tr>
                                                                    <th scope="col">Date & Time</th>
                                                                    <th scope="col">Action</th>
                                                                    <th scope="col">User</th>
                                                                    <th scope="col">Details</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                $sql = "SELECT 
                                                                    al.*,
                                                                    u.full_name as user_name
                                                                FROM activity_log al
                                                                LEFT JOIN users u ON al.user_id = u.user_id
                                                                WHERE al.table_name = 'pre_authorization' 
                                                                AND al.record_id = ?
                                                                ORDER BY al.action_date DESC";
                                                                
                                                                $stmt = $conn->prepare($sql);
                                                                $stmt->bind_param('s', $code);
                                                                $stmt->execute();
                                                                $activities = $stmt->get_result();
                                                                
                                                                if ($activities->num_rows === 0): ?>
                                                                    <tr>
                                                                        <td colspan="4" class="text-center">No activity records found</td>
                                                                    </tr>
                                                                <?php else:
                                                                    while ($activity = $activities->fetch_assoc()): 
                                                                        $action_class = '';
                                                                        switch($activity['action']) {
                                                                            case 'CREATE':
                                                                                $action_class = 'text-success';
                                                                                break;
                                                                            case 'UPDATE':
                                                                                $action_class = 'text-primary';
                                                                                break;
                                                                            case 'DELETE':
                                                                                $action_class = 'text-danger';
                                                                                break;
                                                                        }
                                                                ?>
                                                                    <tr>
                                                                        <td>
                                                                            <?php echo date('d M Y H:i', strtotime($activity['action_date'])); ?>
                                                                        </td>
                                                                        <td>
                                                                            <span class="<?php echo $action_class; ?>">
                                                                                <?php echo $activity['action']; ?>
                                                                            </span>
                                                                        </td>
                                                                        <td><?php echo htmlspecialchars($activity['user_name']); ?></td>
                                                                        <td><?php echo htmlspecialchars($activity['additional_info']); ?></td>
                                                                    </tr>
                                                                <?php endwhile;
                                                                endif; ?>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    <!-- Claims History -->
<div class="row mt-4">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Claims History</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table align-middle table-nowrap mb-0">
                        <thead>
                            <tr>
                                <th scope="col">Claim Number</th>
                                <th scope="col">Date</th>
                                <th scope="col">Provider</th>
                                <th scope="col">Service</th>
                                <th scope="col" class="text-end">Amount</th>
                                <th scope="col">Status</th>
                                <th scope="col">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $sql = "SELECT 
                                b.*,
                                p.provider_name,
                                s.service
                            FROM bills b
                            LEFT JOIN providers p ON b.provider = p.provider_id
                            LEFT JOIN services s ON b.service = s.code
                            WHERE b.member_no = ?
                            ORDER BY b.invoice_date DESC";
                            
                            $stmt = $conn->prepare($sql);
                            $stmt->bind_param('s', $pre_auth['member_no']);
                            $stmt->execute();
                            $claims = $stmt->get_result();
                            
                            if ($claims->num_rows === 0): ?>
                                <tr>
                                    <td colspan="7" class="text-center">No claims found</td>
                                </tr>
                            <?php else:
                                while ($claim = $claims->fetch_assoc()): 
                                    $status_class = '';
                                    $status_text = '';
                                    
                                    switch($claim['vet_status']) {
                                        case 0:
                                            $status_class = 'bg-warning text-dark';
                                            $status_text = 'Pending';
                                            break;
                                        case 1:
                                            $status_class = 'bg-success';
                                            $status_text = 'Approved';
                                            break;
                                        case 2:
                                            $status_class = 'bg-danger';
                                            $status_text = 'Rejected';
                                            break;
                                    }
                            ?>
                                <tr>
                                    <td>
                                        <a href="view_claim.php?id=<?php echo $claim['claim_no']; ?>" 
                                           class="text-primary fw-medium">
                                            <?php echo $claim['claim_no']; ?>
                                        </a>
                                    </td>
                                    <td><?php echo date('d M Y', strtotime($claim['invoice_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($claim['provider_name']); ?></td>
                                    <td><?php echo htmlspecialchars($claim['service']); ?></td>
                                    <td class="text-end">
                                        <?php echo number_format($claim['invoiced_amount'], 2); ?>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo $status_class; ?>">
                                            <?php echo $status_text; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="dropdown">
                                            <a href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" 
                                               aria-expanded="false">
                                                <i class="ri-more-2-fill"></i>
                                            </a>
                                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                                                <li>
                                                    <a class="dropdown-item" href="view_claim.php?id=<?php echo $claim['claim_no']; ?>">
                                                        <i class="ri-eye-line align-middle me-1"></i> View
                                                    </a>
                                                </li>
                                                <?php if ($claim['vet_status'] === 0): ?>
                                                <li>
                                                    <a class="dropdown-item" href="vet_claim.php?id=<?php echo $claim['claim_no']; ?>">
                                                        <i class="ri-check-double-line align-middle me-1"></i> Vet
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                                <li>
                                                    <a class="dropdown-item" href="print_claim.php?id=<?php echo $claim['claim_no']; ?>" 
                                                       target="_blank">
                                                        <i class="ri-printer-line align-middle me-1"></i> Print
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile;
                            endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Admission History -->
<?php if ($pre_auth['authority_type'] == 1): ?>
<div class="row mt-4">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Admission History</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table align-middle table-nowrap mb-0">
                        <thead>
                            <tr>
                                <th scope="col">Admission Date</th>
                                <th scope="col">Discharge Date</th>
                                <th scope="col">Provider</th>
                                <th scope="col">Diagnosis</th>
                                <th scope="col">Days</th>
                                <th scope="col">Ward/Room</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $sql = "SELECT 
                                ca.*,
                                p.provider_name
                            FROM care_admission ca
                            LEFT JOIN providers p ON ca.provider = p.provider_id
                            WHERE ca.member_no = ?
                            ORDER BY ca.date_admitted DESC";
                            
                            $stmt = $conn->prepare($sql);
                            $stmt->bind_param('s', $pre_auth['member_no']);
                            $stmt->execute();
                            $admissions = $stmt->get_result();
                            
                            if ($admissions->num_rows === 0): ?>
                                <tr>
                                    <td colspan="6" class="text-center">No admission records found</td>
                                </tr>
                            <?php else:
                                while ($admission = $admissions->fetch_assoc()): 
                                    $days = '-';
                                    if ($admission['date_discharged']) {
                                        $date1 = new DateTime($admission['date_admitted']);
                                        $date2 = new DateTime($admission['date_discharged']);
                                        $days = $date2->diff($date1)->days;
                                    }
                            ?>
                                <tr>
                                    <td><?php echo date('d M Y', strtotime($admission['date_admitted'])); ?></td>
                                    <td>
                                        <?php echo $admission['date_discharged'] ? 
                                            date('d M Y', strtotime($admission['date_discharged'])) : 'Not Discharged'; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($admission['provider_name']); ?></td>
                                    <td><?php echo htmlspecialchars($admission['diagnosis']); ?></td>
                                    <td><?php echo $days; ?></td>
                                    <td>
                                        Ward: <?php echo htmlspecialchars($admission['ward']); ?><br>
                                        Room: <?php echo htmlspecialchars($admission['room_no']); ?>
                                    </td>
                                </tr>
                            <?php endwhile;
                            endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
<!-- Page Scripts -->
<script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize all tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Back button handler
    document.getElementById('backBtn')?.addEventListener('click', function() {
        window.location.href = 'all_preauth.php';
    });
    
    // Print button handler  
    document.getElementById('printBtn')?.addEventListener('click', function() {
        window.open('print_pre_auth.php?code=<?php echo $code; ?>', '_blank');
    });

    // Edit button handler (admin only)
    document.getElementById('editBtn')?.addEventListener('click', function() {
        window.location.href = 'edit_pre_auth.php?code=<?php echo $code; ?>';
    });

    // Claims table search
    document.getElementById('searchClaims')?.addEventListener('keyup', function() {
        let searchText = this.value.toLowerCase();
        let rows = document.querySelectorAll('#claimsTable tbody tr');
        
        rows.forEach(row => {
            let text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchText) ? '' : 'none';
        });
    });

    // Date range filter for claims
    const dateFrom = document.getElementById('dateFrom');
    const dateTo = document.getElementById('dateTo');
    
    function filterByDate() {
        if (!dateFrom?.value || !dateTo?.value) return;
        
        let fromDate = new Date(dateFrom.value);
        let toDate = new Date(dateTo.value);
        
        let rows = document.querySelectorAll('#claimsTable tbody tr');
        
        rows.forEach(row => {
            let dateCell = row.cells[1]?.textContent; // Assuming date is in second column
            if (dateCell) {
                let rowDate = new Date(dateCell);
                row.style.display = (rowDate >= fromDate && rowDate <= toDate) ? '' : 'none';
            }
        });
    }
    
    dateFrom?.addEventListener('change', filterByDate);
    dateTo?.addEventListener('change', filterByDate);

    // Export table data
    document.getElementById('exportBtn')?.addEventListener('click', function() {
        let table = document.getElementById('claimsTable');
        if (!table) return;

        let csv = [];
        let rows = table.querySelectorAll('tr');
        
        rows.forEach(row => {
            let rowData = [];
            row.querySelectorAll('td, th').forEach(cell => {
                rowData.push('"' + cell.textContent.trim().replace(/"/g, '""') + '"');
            });
            csv.push(rowData.join(','));
        });

        let csvContent = 'data:text/csv;charset=utf-8,' + csv.join('\n');
        let encodedUri = encodeURI(csvContent);
        let link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', 'claims_history.csv');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
});
</script>
<script>
        function createClaimFromPreAuth(preAuthCode) {
    Swal.fire({
        title: 'Create Claim',
        text: 'Do you want to create a claim from this pre-authorization?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, create claim',
        cancelButtonText: 'No, cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Get pre-auth details
            fetch(`get_preauth_details.php?code=${preAuthCode}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Redirect to claim entry page with pre-auth data
                        const params = new URLSearchParams({
                            pre_auth_code: data.pre_auth.code,
                            member_no: data.pre_auth.member_no,
                            provider: data.pre_auth.provider,
                            service: data.pre_auth.authority_type,
                            amount: data.pre_auth.reserve,
                            diagnosis: data.pre_auth.pre_diagnosis
                        });
                        window.location.href = `add_new_claim.php?${params.toString()}`;
                    } else {
                        throw new Error(data.error);
                    }
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                });
        }
    });
}
</script>
</body>
</html>