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

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

$member = null;
$riskData = null;
$recommendations = null;
$monitoringData = null;

// Get member number from query string or search form
$member_no = $_GET['member_no'] ?? null;
$searchTerm = $_GET['search'] ?? '';

if ($searchTerm) {
    // Search for members
    $sql = "SELECT m.*, c.corporate 
            FROM member_info m 
            JOIN corporate c ON m.corp_id = c.corp_id 
            WHERE m.member_no LIKE ? 
            OR m.surname LIKE ? 
            OR m.first_name LIKE ?
            OR CONCAT(m.surname, ' ', m.first_name) LIKE ?
            LIMIT 10";
            
    $searchParam = "%$searchTerm%";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ssss', $searchParam, $searchParam, $searchParam, $searchParam);
    $stmt->execute();
    $searchResults = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

// If member number is provided, get risk profile data
if ($member_no) {
    try {
        // Initialize risk profile
        $riskProfile = new MemberRiskProfile($conn, $member_no);
        
        // Get risk assessment data
        $riskData = $riskProfile->calculateHealthRiskScore();
        $recommendations = $riskProfile->getInterventionRecommendations();
        $monitoringData = $riskProfile->monitorChronicConditions();

        // Get member details
        $sql = "SELECT m.*, c.corporate 
                FROM member_info m 
                JOIN corporate c ON m.corp_id = c.corp_id 
                WHERE m.member_no = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('s', $member_no);
        $stmt->execute();
        $member = $stmt->get_result()->fetch_assoc();

    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Member Risk Profile')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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' => 'Risk Profile', 'title' => 'Member Risk Assessment')); ?>
                    <!-- Search Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Search Member</h4>
                                </div>
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-lg-8">
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($searchTerm); ?>"
                                                   placeholder="Enter member number, name or surname">
                                        </div>
                                        <div class="col-lg-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-search-line align-middle me-1"></i> Search
                                            </button>
                                        </div>
                                    </form>

                                    <?php if (!empty($searchResults)): ?>
                                    <div class="table-responsive mt-4">
                                        <table class="table table-bordered table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Member No</th>
                                                    <th>Name</th>
                                                    <th>Corporate</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($searchResults as $result): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($result['member_no']); ?></td>
                                                    <td><?php echo htmlspecialchars($result['surname'] . ' ' . $result['first_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($result['corporate']); ?></td>
                                                    <td>
                                                        <a href="?member_no=<?php echo urlencode($result['member_no']); ?>" 
                                                           class="btn btn-sm btn-primary">
                                                            View Risk Profile
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php elseif ($searchTerm): ?>
                                    <div class="alert alert-info mt-4">
                                        No members found matching your search criteria.
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <!-- Member Info Card -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Member Information</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tr>
                                                <th width="140">Member No:</th>
                                                <td><?php echo htmlspecialchars($member['member_no']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Name:</th>
                                                <td><?php echo htmlspecialchars($member['surname'] . ' ' . $member['first_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Corporate:</th>
                                                <td><?php echo htmlspecialchars($member['corporate']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Risk Level:</th>
                                                <td>
                                                    <span class="badge bg-<?php 
                                                        echo $riskData['risk_level'] === 'HIGH' ? 'danger' : 
                                                            ($riskData['risk_level'] === 'LOW' ? 'success' : 
                                                            'warning'); ?>">
                                                        <?php echo $riskData['risk_level']; ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <a href="download_risk_report.php?member_no=<?php echo urlencode($member_no); ?>" 
                                           class="btn btn-primary w-100">
                                            <i class="ri-file-download-line align-middle me-1"></i>
                                            Download Risk Assessment Report
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Risk Score Card -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Risk Factor Analysis</h4>
                                </div>
                                <div class="card-body">
                                    <canvas id="riskRadarChart" height="250"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Recommendations -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recommended Interventions</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($recommendations)): ?>
                                        <div class="text-center text-muted">
                                            <i class="ri-checkbox-circle-line display-4"></i>
                                            <p class="mt-2">No interventions recommended at this time.</p>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach ($recommendations as $rec): ?>
                                            <div class="mb-4">
                                                <div class="d-flex align-items-center mb-2">
                                                    <span class="badge bg-<?php 
                                                        echo $rec['priority'] === 'HIGH' ? 'danger' : 
                                                            ($rec['priority'] === 'LOW' ? 'success' : 'warning'); ?> me-2">
                                                        <?php echo $rec['priority']; ?>
                                                    </span>
                                                    <h5 class="mb-0"><?php echo $rec['type']; ?></h5>
                                                </div>
                                                <p class="mb-1"><?php echo htmlspecialchars($rec['description']); ?></p>
                                                <small class="text-muted">
                                                    <i class="ri-arrow-right-line"></i>
                                                    <?php echo htmlspecialchars($rec['action']); ?>
                                                </small>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Chronic Conditions -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Chronic Condition Monitoring</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($monitoringData)): ?>
                                        <div class="text-center text-muted">
                                            <i class="ri-heart-pulse-line display-4"></i>
                                            <p class="mt-2">No chronic conditions to monitor.</p>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach ($monitoringData as $condition): ?>
                                            <div class="mb-4">
                                                <h5><?php echo htmlspecialchars($condition['condition']); ?></h5>
                                                <div class="table-responsive">
                                                    <table class="table table-sm">
                                                        <tr>
                                                            <th width="140">Diagnosed:</th>
                                                            <td><?php echo date('d M Y', strtotime($condition['diagnosis_date'])); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>Last Checkup:</th>
                                                            <td><?php echo date('d M Y', strtotime($condition['last_checkup'])); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th>Next Due:</th>
                                                            <td>
                                                                <?php 
                                                                $next_checkup = strtotime($condition['next_checkup_due']);
                                                                $is_overdue = $next_checkup < time();
                                                                ?>
                                                                <span class="<?php echo $is_overdue ? 'text-danger' : ''; ?>">
                                                                    <?php echo date('d M Y', $next_checkup); ?>
                                                                    <?php if ($is_overdue): ?>
                                                                        <i class="ri-error-warning-line align-middle ms-1"></i>
                                                                    <?php endif; ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </div>

                                                <?php if (!empty($condition['alerts'])): ?>
                                                    <div class="alert alert-warning mb-0 mt-2">
                                                        <ul class="mb-0">
                                                            <?php foreach ($condition['alerts'] as $alert): ?>
                                                                <li><?php echo htmlspecialchars($alert['message']); ?></li>
                                                            <?php endforeach; ?>
                                                        </ul>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        // Initialize radar chart for risk scores
        const ctx = document.getElementById('riskRadarChart').getContext('2d');
        const riskScores = <?php echo json_encode($riskData['detailed_scores']); ?>;
        
        new Chart(ctx, {
            type: 'radar',
            data: {
                labels: [
                    'Age Risk',
                    'BMI Risk',
                    'Chronic Conditions',
                    'Lifestyle Risk',
                    'Family History',
                    'Claims History'
                ],
                datasets: [{
                    label: 'Risk Factors',
                    data: [
                        riskScores.age_score,
                        riskScores.bmi_score,
                        riskScores.chronic_score,
                        riskScores.lifestyle_score,
                        riskScores.family_score,
                        riskScores.claims_score
                    ],
                    fill: true,
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgb(54, 162, 235)',
                    pointBackgroundColor: 'rgb(54, 162, 235)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgb(54, 162, 235)'
                }]
            },
            options: {
                scales: {
                    r: {
                        min: 0,
                        max: 5,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                elements: {
                    line: {
                        borderWidth: 3
                    }
                }
            }
        });
    </script>
</body>
</html>