<?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 for navbar
$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;
    }
}

$msg = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $dob = $_POST['dob'];
    $gender = $_POST['gender'];
    $blood_group = $conn->real_escape_string($_POST['blood_group']);
    $allergies = $conn->real_escape_string($_POST['allergies']);
    
    $stmt = $conn->prepare("UPDATE patients SET date_of_birth=?, gender=?, blood_group=?, allergies=? WHERE patient_id=?");
    $stmt->bind_param("sssss", $dob, $gender, $blood_group, $allergies, $patient_id);
    if ($stmt->execute()) {
        $msg = "Profile updated successfully!";
        $_SESSION['success'] = $msg;
    } else {
        $error = "Update failed: " . $conn->error;
    }
    $stmt->close();
}

// Fetch current data
$p = $conn->query("SELECT * FROM patients WHERE patient_id='$patient_id'")->fetch_assoc();
?>
<!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>Complete Profile - 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-primary { background: #0f6b4c; border: none; border-radius: 30px; padding: 10px; }
        .btn-primary:hover { background: #0a523b; }
        .form-control, .form-select { border-radius: 12px; padding: 10px 15px; }
        .btn-light { border-radius: 30px; }
        @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-edit me-2"></i> Complete Profile</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-user-plus me-2"></i> Additional Information
        </div>
        <div class="card-body">
            <?php if(isset($_SESSION['success'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST">
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="far fa-calendar-alt me-1"></i> Date of Birth</label>
                    <input type="date" name="dob" class="form-control" value="<?php echo htmlspecialchars($p['date_of_birth'] ?? ''); ?>">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-venus-mars me-1"></i> Gender</label>
                    <select name="gender" class="form-select">
                        <option value="Male" <?php echo ($p['gender'] ?? '') == 'Male' ? 'selected' : ''; ?>>Male</option>
                        <option value="Female" <?php echo ($p['gender'] ?? '') == 'Female' ? 'selected' : ''; ?>>Female</option>
                        <option value="Other" <?php echo ($p['gender'] ?? '') == 'Other' ? 'selected' : ''; ?>>Other</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-tint me-1"></i> Blood Group</label>
                    <input type="text" name="blood_group" class="form-control" value="<?php echo htmlspecialchars($p['blood_group'] ?? ''); ?>" placeholder="e.g., A+, O-, B+">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold"><i class="fas fa-allergies me-1"></i> Allergies</label>
                    <textarea name="allergies" class="form-control" rows="3" placeholder="List any allergies you have..."><?php echo htmlspecialchars($p['allergies'] ?? ''); ?></textarea>
                </div>
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-save me-2"></i> Save Information
                </button>
            </form>
        </div>
    </div>
</div>

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