<?php
session_start();
include '../config/database.php';

// Check if user is logged in and is a doctor
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'Doctor') {
    header("Location: /doctor/login.php");
    exit();
}

$doctor_id = $_SESSION['user_id'];
$page_title = "Patient Record";

// Get patient ID from URL
$patient_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Verify this patient is assigned to this doctor
$check_query = "SELECT p.* FROM patients p 
                JOIN appointments a ON p.patient_id = a.patient_id 
                WHERE p.patient_id = $patient_id AND a.doctor_id = $doctor_id 
                LIMIT 1";
$result = $conn->query($check_query);

if ($result && $result->num_rows > 0) {
    $patient = $result->fetch_assoc();
} else {
    // Patient not found or not assigned to this doctor
    header("Location: my_patients.php?error=invalid_patient");
    exit();
}

// Handle prescription submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_prescription'])) {
    $medication = $conn->real_escape_string($_POST['medication']);
    $dosage = $conn->real_escape_string($_POST['dosage']);
    $frequency = $conn->real_escape_string($_POST['frequency']);
    $duration = $conn->real_escape_string($_POST['duration']);
    $instructions = $conn->real_escape_string($_POST['instructions']);
    
    $stmt = $conn->prepare("INSERT INTO prescriptions (patient_id, doctor_id, medication, dosage, frequency, duration, instructions, prescribed_date) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("iisssss", $patient_id, $doctor_id, $medication, $dosage, $frequency, $duration, $instructions);
    
    if ($stmt->execute()) {
        $success = "Prescription added successfully!";
    } else {
        $error = "Error adding prescription: " . $conn->error;
    }
    $stmt->close();
}

// Handle vitals submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_vitals'])) {
    $blood_pressure = $conn->real_escape_string($_POST['blood_pressure']);
    $heart_rate = (int)$_POST['heart_rate'];
    $temperature = (float)$_POST['temperature'];
    $weight = (float)$_POST['weight'];
    $height = (float)$_POST['height'];
    $notes = $conn->real_escape_string($_POST['vitals_notes']);
    
    $stmt = $conn->prepare("INSERT INTO vitals (patient_id, doctor_id, blood_pressure, heart_rate, temperature, weight, height, notes, recorded_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("iisiddds", $patient_id, $doctor_id, $blood_pressure, $heart_rate, $temperature, $weight, $height, $notes);
    
    if ($stmt->execute()) {
        $success = "Vitals recorded successfully!";
    } else {
        $error = "Error recording vitals: " . $conn->error;
    }
    $stmt->close();
}

// Get prescriptions
$prescriptions = $conn->query("SELECT * FROM prescriptions WHERE patient_id = $patient_id ORDER BY prescribed_date DESC");

// Get vitals
$vitals = $conn->query("SELECT * FROM vitals WHERE patient_id = $patient_id ORDER BY recorded_date DESC LIMIT 10");

// Get medical history
$medical_history = $conn->query("SELECT * FROM medical_history WHERE patient_id = $patient_id ORDER BY diagnosis_date DESC");

// Get appointments
$appointments = $conn->query("SELECT * FROM appointments WHERE patient_id = $patient_id AND doctor_id = $doctor_id ORDER BY appointment_date DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Patient Record - <?php echo htmlspecialchars($patient['first_name'] . ' ' . $patient['last_name']); ?></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>
        .info-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .section-header {
            background: #0b2f2f;
            color: white;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .prescription-item {
            border-left: 4px solid #28a745;
            padding: 12px;
            margin-bottom: 12px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .vital-box {
            display: inline-block;
            background: white;
            padding: 10px;
            margin: 5px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-2 d-md-block bg-dark text-white min-vh-100 p-3">
                <h4 class="text-center mb-4">Doctor Portal</h4>
                <div class="text-center mb-4">
                    <i class="fas fa-user-md fa-3x"></i>
                    <p class="mt-2">Dr. <?php echo htmlspecialchars($_SESSION['full_name'] ?? $_SESSION['username']); ?></p>
                </div>
                <hr>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link text-white" href="dashboard.php">
                            <i class="fas fa-tachometer-alt"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="my_patients.php">
                            <i class="fas fa-users"></i> My Patients
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white active" href="patient_records.php">
                            <i class="fas fa-folder-open"></i> Patient Records
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="prescriptions.php">
                            <i class="fas fa-prescription-bottle"></i> Prescriptions
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="record_vitals.php">
                            <i class="fas fa-heartbeat"></i> Record Vitals
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white" href="sessions.php">
                            <i class="fas fa-calendar-alt"></i> Sessions
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-danger" href="../logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </li>
                </ul>
            </nav>

            <!-- Main Content -->
            <main class="col-md-10 ms-sm-auto px-md-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                    <h1>Patient Record</h1>
                    <a href="my_patients.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to My Patients
                    </a>
                </div>

                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Patient Information -->
                <div class="info-card">
                    <h4><i class="fas fa-user-circle"></i> Patient Information</h4>
                    <hr>
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>Full Name:</strong> <?php echo htmlspecialchars($patient['first_name'] . ' ' . ($patient['last_name'] ?? '')); ?></p>
                            <p><strong>Email:</strong> <?php echo htmlspecialchars($patient['email'] ?? 'N/A'); ?></p>
                            <p><strong>Phone:</strong> <?php echo htmlspecialchars($patient['phone'] ?? 'N/A'); ?></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>Date of Birth:</strong> <?php echo isset($patient['date_of_birth']) ? date('F d, Y', strtotime($patient['date_of_birth'])) : 'N/A'; ?></p>
                            <p><strong>Gender:</strong> <?php echo htmlspecialchars($patient['gender'] ?? 'N/A'); ?></p>
                            <p><strong>Blood Group:</strong> <?php echo htmlspecialchars($patient['blood_group'] ?? 'N/A'); ?></p>
                        </div>
                    </div>
                </div>

                <!-- Record Vitals Section -->
                <div class="section-header">
                    <h5 class="mb-0"><i class="fas fa-heartbeat"></i> Record Vitals</h5>
                </div>
                <div class="info-card">
                    <form method="POST">
                        <div class="row">
                            <div class="col-md-3 mb-2">
                                <label>Blood Pressure</label>
                                <input type="text" name="blood_pressure" class="form-control" placeholder="120/80" required>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label>Heart Rate (bpm)</label>
                                <input type="number" name="heart_rate" class="form-control" placeholder="72" required>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label>Temperature (°F)</label>
                                <input type="number" step="0.1" name="temperature" class="form-control" placeholder="98.6" required>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label>Weight (kg)</label>
                                <input type="number" step="0.1" name="weight" class="form-control" placeholder="70">
                            </div>
                            <div class="col-md-3 mb-2">
                                <label>Height (cm)</label>
                                <input type="number" step="0.1" name="height" class="form-control" placeholder="170">
                            </div>
                            <div class="col-md-9 mb-2">
                                <label>Notes</label>
                                <input type="text" name="vitals_notes" class="form-control" placeholder="Additional notes...">
                            </div>
                        </div>
                        <button type="submit" name="update_vitals" class="btn btn-primary mt-2">Save Vitals</button>
                    </form>
                </div>

                <!-- Vitals History -->
                <div class="section-header mt-3">
                    <h5 class="mb-0"><i class="fas fa-chart-line"></i> Recent Vitals History</h5>
                </div>
                <div class="info-card">
                    <?php if ($vitals && $vitals->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Blood Pressure</th>
                                        <th>Heart Rate</th>
                                        <th>Temperature</th>
                                        <th>Weight</th>
                                        <th>Notes</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($vital = $vitals->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo date('M d, Y g:i A', strtotime($vital['recorded_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($vital['blood_pressure'] ?? 'N/A'); ?></td>
                                        <td><?php echo $vital['heart_rate'] ?? 'N/A'; ?></td>
                                        <td><?php echo isset($vital['temperature']) ? $vital['temperature'] . '°F' : 'N/A'; ?></td>
                                        <td><?php echo isset($vital['weight']) ? $vital['weight'] . ' kg' : 'N/A'; ?></td>
                                        <td><?php echo htmlspecialchars($vital['notes'] ?? 'N/A'); ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <p class="text-muted">No vitals recorded yet.</p>
                    <?php endif; ?>
                </div>

                <!-- Prescriptions Section -->
                <div class="section-header mt-3">
                    <h5 class="mb-0"><i class="fas fa-prescription-bottle"></i> Prescriptions</h5>
                </div>
                
                <!-- Add Prescription -->
                <div class="info-card">
                    <h6>Add New Prescription</h6>
                    <form method="POST">
                        <div class="row">
                            <div class="col-md-3 mb-2">
                                <label>Medication</label>
                                <input type="text" name="medication" class="form-control" required>
                            </div>
                            <div class="col-md-2 mb-2">
                                <label>Dosage</label>
                                <input type="text" name="dosage" class="form-control" placeholder="500mg" required>
                            </div>
                            <div class="col-md-2 mb-2">
                                <label>Frequency</label>
                                <input type="text" name="frequency" class="form-control" placeholder="Twice daily" required>
                            </div>
                            <div class="col-md-2 mb-2">
                                <label>Duration</label>
                                <input type="text" name="duration" class="form-control" placeholder="7 days" required>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label>Instructions</label>
                                <input type="text" name="instructions" class="form-control" placeholder="Take with food">
                            </div>
                        </div>
                        <button type="submit" name="add_prescription" class="btn btn-success mt-2">Add Prescription</button>
                    </form>
                </div>

                <!-- Prescription History -->
                <div class="info-card">
                    <h6>Prescription History</h6>
                    <?php if ($prescriptions && $prescriptions->num_rows > 0): ?>
                        <?php while($prescription = $prescriptions->fetch_assoc()): ?>
                            <div class="prescription-item">
                                <strong><?php echo htmlspecialchars($prescription['medication']); ?></strong>
                                <br>
                                <small>
                                    <i class="fas fa-capsules"></i> <?php echo htmlspecialchars($prescription['dosage']); ?> | 
                                    <i class="fas fa-clock"></i> <?php echo htmlspecialchars($prescription['frequency']); ?> | 
                                    <i class="fas fa-calendar-week"></i> <?php echo htmlspecialchars($prescription['duration']); ?>
                                </small>
                                <?php if (!empty($prescription['instructions'])): ?>
                                    <br><small class="text-muted"><i class="fas fa-info-circle"></i> <?php echo htmlspecialchars($prescription['instructions']); ?></small>
                                <?php endif; ?>
                                <br><small class="text-muted">Prescribed: <?php echo date('F d, Y', strtotime($prescription['prescribed_date'])); ?></small>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <p class="text-muted">No prescriptions yet.</p>
                    <?php endif; ?>
                </div>

                <!-- Medical History -->
                <div class="section-header mt-3">
                    <h5 class="mb-0"><i class="fas fa-history"></i> Medical History</h5>
                </div>
                <div class="info-card">
                    <?php if ($medical_history && $medical_history->num_rows > 0): ?>
                        <?php while($history = $medical_history->fetch_assoc()): ?>
                            <div class="mb-3 p-3 border rounded">
                                <strong><?php echo date('M d, Y', strtotime($history['diagnosis_date'])); ?> - <?php echo htmlspecialchars($history['condition_name'] ?? 'N/A'); ?></strong>
                                <p class="mb-1"><?php echo htmlspecialchars($history['description'] ?? 'No description'); ?></p>
                                <?php if (!empty($history['doctor_name'])): ?>
                                    <small class="text-muted">Treated by: Dr. <?php echo htmlspecialchars($history['doctor_name']); ?></small>
                                <?php endif; ?>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <p class="text-muted">No medical history recorded.</p>
                    <?php endif; ?>
                </div>

                <!-- Appointment History -->
                <div class="section-header mt-3">
                    <h5 class="mb-0"><i class="fas fa-calendar-check"></i> Appointment History</h5>
                </div>
                <div class="info-card">
                    <?php if ($appointments && $appointments->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Time</th>
                                        <th>Reason</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($appointment = $appointments->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo date('M d, Y', strtotime($appointment['appointment_date'])); ?></td>
                                        <td><?php echo date('g:i A', strtotime($appointment['appointment_time'])); ?></td>
                                        <td><?php echo htmlspecialchars($appointment['reason'] ?? 'N/A'); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $appointment['status'] == 'scheduled' ? 'success' : ($appointment['status'] == 'completed' ? 'info' : 'secondary'); ?>">
                                                <?php echo ucfirst($appointment['status'] ?? 'N/A'); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <p class="text-muted">No appointment history.</p>
                    <?php endif; ?>
                </div>
            </main>
        </div>
    </div>

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