<!-- claim_status.php -->
<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$claim_no = $_GET['claim_no'] ?? '';
$claim_details = null;
$timeline = [];

if ($claim_no) {
    // Get claim details grouped by claim number
    $sql = "SELECT 
                b.claim_no,
                GROUP_CONCAT(b.invoice_no) as invoice_nos,
                GROUP_CONCAT(b.service) as services,
                SUM(b.invoiced_amount) as total_amount,
                m.surname, 
                m.first_name, 
                c.corporate,
                MIN(b.date_entered) as claim_date,
                b.member_no,
                b.corp_id
            FROM bills b
            LEFT JOIN member_info m ON b.member_no = m.member_no
            LEFT JOIN corporate c ON b.corp_id = c.corp_id
            WHERE b.claim_no = ?
            GROUP BY b.claim_no, m.surname, m.first_name, c.corporate, b.member_no, b.corp_id";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $claim_no);
    $stmt->execute();
    $claim_details = $stmt->get_result()->fetch_assoc();

   if ($claim_details) {
    // Get status timeline
    $sql = "SELECT 
            csl.*, 
            u.full_name,
            GROUP_CONCAT(DISTINCT csl.invoice_no) as affected_invoices
        FROM claim_status_log csl
        LEFT JOIN users u ON csl.user_id = u.user_id
        WHERE csl.claim_no = ?
        GROUP BY csl.status_code, csl.created_at
        ORDER BY csl.created_at DESC";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $claim_no);
    $stmt->execute();
    $timeline = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    // Get services for each invoice if needed
    foreach ($timeline as &$status) {
        if (!empty($status['affected_invoices'])) {
            $invoice_nos = explode(',', $status['affected_invoices']);
            $in_params = str_repeat('?,', count($invoice_nos) - 1) . '?';
            
            $sql = "SELECT DISTINCT s.service 
                    FROM bills b
                    JOIN services s ON b.service = s.code
                    WHERE b.invoice_no IN ($in_params)
                    AND b.claim_no = ?";
            
            $stmt = $conn->prepare($sql);
            $params = array_merge($invoice_nos, [$claim_no]);
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $services_result = $stmt->get_result();
            
            $services = [];
            while ($row = $services_result->fetch_assoc()) {
                $services[] = $row['service'];
            }
            $status['services'] = implode(', ', $services);
        }
    }
}
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Claim Status Timeline')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .timeline {
            position: relative;
            padding: 20px 0;
        }
        .timeline-item {
            padding: 20px 30px;
            border-left: 2px solid #e9ecef;
            position: relative;
        }
        .timeline-item:before {
            content: '';
            position: absolute;
            left: -9px;
            top: 28px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: #fff;
            border: 2px solid #3688fc;
        }
        .timeline-item.completed:before {
            background: #0ab39c;
            border-color: #0ab39c;
        }
        .timeline-item.active:before {
            background: #3688fc;
            border-color: #3688fc;
        }
        .timeline-item.pending:before {
            background: #fff;
            border-color: #f7b84b;
        }
    </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' => 'Claims', 'title' => 'Claim Status Timeline')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Search Claim</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Claim Number</label>
                                            <div class="input-group">
                                                <input type="text" class="form-control" name="claim_no" 
                                                       value="<?php echo htmlspecialchars($claim_no); ?>" required>
                                                <button class="btn btn-primary" type="submit">
                                                    <i class="ri-search-line"></i> Search
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <?php if ($claim_details): ?>
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Claim Details</h4>
                                </div>
                                
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <table class="table table-sm table-borderless mb-0">
                                                <tr>
                                                    <th width="150">Claim Number:</th>
                                                    <td><?php echo $claim_details['claim_no']; ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Member Name:</th>
                                                    <td><?php echo $claim_details['surname'] . ' ' . $claim_details['first_name']; ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Corporate:</th>
                                                    <td><?php echo $claim_details['corporate']; ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <table class="table table-sm table-borderless mb-0">
                                                <tr>
                                                    <th width="150">Invoice Number:</th>
                                                    <td><?php echo $claim_details['invoice_no']; ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Invoice Date:</th>
                                                    <td><?php echo date('d M Y', strtotime($claim_details['invoice_date'])); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Amount:</th>
                                                    <td><?php echo number_format($claim_details['invoiced_amount'], 2); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Status Timeline</h4>
                                </div>
                                
                                <div class="card-body">
                                   <div class="timeline-item <?php 
                                        echo $status['completed'] ? 'completed' : 
                                            ($status['active'] ? 'active' : 'pending'); 
                                    ?>">
                                        <h5 class="fw-bold"><?php echo $status['status_name']; ?></h5>
                                        <p class="text-muted mb-2">
                                            <?php echo $status['remarks']; ?>
                                            <?php if (!empty($status['affected_invoices'])): ?>
                                                <br>
                                                <small>
                                                    <?php if (!empty($status['services'])): ?>
                                                        Services: <?php echo htmlspecialchars($status['services']); ?><br>
                                                    <?php endif; ?>
                                                    Invoice(s): <?php echo htmlspecialchars($status['affected_invoices']); ?>
                                                </small>
                                            <?php endif; ?>
                                        </p>
                                        <p class="text-muted mb-0">
                                            <small>
                                                <?php echo date('d M Y H:i', strtotime($status['created_at'])); ?> 
                                                by <?php echo htmlspecialchars($status['full_name']); ?>
                                            </small>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <?php elseif ($claim_no): ?>
                                <div class="alert alert-danger">
                                    No claim found with the number: <?php echo htmlspecialchars($claim_no); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    // Add this to your existing claim_status.php file
<script>
function refreshTimeline() {
    const claimNo = '<?php echo htmlspecialchars($claim_no); ?>';
    if (!claimNo) return;

    fetch(`get_claim_timeline.php?claim_no=${claimNo}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const timelineContainer = document.querySelector('.timeline');
                timelineContainer.innerHTML = data.timeline.map(status => `
                    <div class="timeline-item ${status.completed ? 'completed' : 
                                              (status.active ? 'active' : 'pending')}">
                        <h5 class="fw-bold">${status.status_name}</h5>
                        <p class="text-muted mb-2">${status.remarks || ''}</p>
                        <p class="text-muted mb-0">
                            <small>
                                ${new Date(status.created_at).toLocaleString()} 
                                by ${status.full_name}
                            </small>
                        </p>
                    </div>
                `).join('');
            }
        })
        .catch(error => console.error('Error refreshing timeline:', error));
}

// Refresh every 30 seconds
setInterval(refreshTimeline, 30000);
</script>
</body>
</html>