<?php
session_start();

// Session security: regenerate ID to prevent fixation
if (!isset($_SESSION['initialized'])) {
    session_regenerate_id(true);
    $_SESSION['initialized'] = true;
}

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

// Session timeout (30 minutes)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}
$_SESSION['LAST_ACTIVITY'] = time();

include '../include/config.php';
$patient_id = $_SESSION['patient_id'];

// Get patient name
$patient_name = $_SESSION['patient_name'] ?? '';
if (empty($patient_name)) {
    $nameQuery = $conn->query("SELECT CONCAT(first_name, ' ', last_name) as name FROM patients WHERE patient_id = '$patient_id'");
    if ($nameQuery && $nameQuery->num_rows) {
        $patient_name = $nameQuery->fetch_assoc()['name'];
        $_SESSION['patient_name'] = $patient_name;
    }
}

// Gather real data for AI summary
$activity_count = 0;
$appointment_count = 0;
$prescription_count = 0;
$vitals_count = 0;
$recent_activities = [];

// Last 7 days activity count
$actResult = $conn->query("SELECT COUNT(*) as cnt FROM daily_activity WHERE patient_id = '$patient_id' AND activity_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
if ($actResult) $activity_count = $actResult->fetch_assoc()['cnt'];

// Upcoming appointments count
$appResult = $conn->query("SELECT COUNT(*) as cnt FROM appointments WHERE patient_id = '$patient_id' AND appointment_date >= CURDATE()");
if ($appResult) $appointment_count = $appResult->fetch_assoc()['cnt'];

// Prescriptions count
$preResult = $conn->query("SELECT COUNT(*) as cnt FROM prescriptions WHERE patient_id = '$patient_id'");
if ($preResult) $prescription_count = $preResult->fetch_assoc()['cnt'];

// Vitals count
$vitResult = $conn->query("SELECT COUNT(*) as cnt FROM vitals WHERE patient_id = '$patient_id'");
if ($vitResult) $vitals_count = $vitResult->fetch_assoc()['cnt'];

// Get last 3 activity types for insight
$activities = $conn->query("SELECT activity_type FROM daily_activity WHERE patient_id = '$patient_id' ORDER BY activity_date DESC LIMIT 3");
if ($activities && $activities->num_rows > 0) {
    while ($a = $activities->fetch_assoc()) {
        $recent_activities[] = $a['activity_type'];
    }
}

// Generate dynamic AI summary
$summary = "Based on your health data: ";
if ($activity_count > 5) {
    $summary .= "You've been very active this week ($activity_count activities). ";
} elseif ($activity_count > 0) {
    $summary .= "You logged $activity_count activities this week. Keep going! ";
} else {
    $summary .= "You haven't logged any activities this week. Start tracking to see insights. ";
}

if ($appointment_count > 0) {
    $summary .= "You have $appointment_count upcoming appointment(s). ";
}

if ($prescription_count > 0) {
    $summary .= "You have $prescription_count prescription(s) on file. ";
}

if ($vitals_count > 0) {
    $summary .= "Your vitals are being monitored. ";
}

if (!empty($recent_activities)) {
    $summary .= "Recent activities: " . implode(", ", $recent_activities) . ". ";
}

$summary .= "Stay healthy with UHD!";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>AI Health Summary - UHD Hospital</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #0a3d2f; font-family: 'Segoe UI', sans-serif; }
        .navbar { background: #064e3b !important; }
        .card { border-radius: 20px; background: rgba(255,255,255,0.95); border: none; }
        .card-header { background: linear-gradient(135deg, #0f6b4c, #064e3b); color: white; border-radius: 20px 20px 0 0; }
        .btn-light { border-radius: 30px; }
        .insight-icon { font-size: 3rem; color: #0f6b4c; }
        .stat-badge { background: #e9ecef; border-radius: 30px; padding: 5px 12px; display: inline-block; margin: 5px; }
        @media (max-width: 768px) { .container { padding: 10px; } }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-robot me-2"></i> AI Health Summary</span>
        <div>
            <span class="text-white me-2 d-none d-sm-inline"><i class="fas fa-user-circle"></i> <?php echo htmlspecialchars($patient_name); ?></span>
            <a href="dashboard.php" class="btn btn-light btn-sm"><i class="fas fa-arrow-left"></i> Back</a>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="card">
        <div class="card-header">
            <i class="fas fa-brain me-2"></i> Your Personalized Health Insight
        </div>
        <div class="card-body text-center">
            <i class="fas fa-chart-line insight-icon mb-3"></i>
            <p class="lead"><?php echo htmlspecialchars($summary); ?></p>
            <hr>
            <div class="row mt-3">
                <div class="col-6 col-md-3">
                    <div class="stat-badge"><i class="fas fa-walking"></i> <?php echo $activity_count; ?> Activities</div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="stat-badge"><i class="fas fa-calendar-check"></i> <?php echo $appointment_count; ?> Appointments</div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="stat-badge"><i class="fas fa-pills"></i> <?php echo $prescription_count; ?> Prescriptions</div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="stat-badge"><i class="fas fa-heartbeat"></i> <?php echo $vitals_count; ?> Vitals</div>
                </div>
            </div>
            <div class="mt-4">
                <i class="fas fa-microchip text-muted"></i> <small class="text-muted">Powered by UHD AI • Real-time analysis</small>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>