<?php
session_start();
if (!isset($_SESSION['doctor_id'])) {
    header("Location: login.php");
    exit();
}
include '../include/config.php';
$doctor_id = $_SESSION['doctor_id'];

$success = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $patient_id = $_POST['patient_id'];
    $scheduled_time = $_POST['scheduled_time'];
    $reason = $_POST['reason'] ?? '';
    $notes = $_POST['notes'] ?? '';
    
    if (empty($patient_id) || empty($scheduled_time)) {
        $error = "Please select a patient and scheduled time.";
    } else {
        $stmt = $conn->prepare("INSERT INTO consultations (doctor_id, patient_id, scheduled_time, reason, notes, status) VALUES (?, ?, ?, ?, ?, 'scheduled')");
        $stmt->bind_param("iisss", $doctor_id, $patient_id, $scheduled_time, $reason, $notes);
        
        if ($stmt->execute()) {
            $consult_id = $conn->insert_id;
            $_SESSION['success'] = "Consultation scheduled successfully!";
            header("Location: consultations.php");
            exit();
        } else {
            $error = "Error scheduling consultation: " . $conn->error;
        }
    }
}

// Get patients list
$patients = $conn->query("SELECT patient_id, first_name, last_name, email, phone FROM patients WHERE portal_active = 1 ORDER BY first_name");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Schedule Consultation - UHD</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: linear-gradient(135deg, #0a3d2f 0%, #064e3b 100%); min-height: 100vh; }
        .card { border-radius: 20px; border: none; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
        .form-control, .form-select { border-radius: 12px; padding: 12px 15px; border: 1px solid #e0e0e0; }
        .form-control:focus, .form-select:focus { border-color: #064e3b; box-shadow: 0 0 0 0.2rem rgba(6, 78, 59, 0.25); }
        .btn-primary { background: #064e3b; border: none; border-radius: 12px; padding: 12px; font-weight: 600; }
        .btn-primary:hover { background: #0a5d46; }
        .time-slots { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 10px; margin-top: 10px; }
        .time-slot { padding: 8px; border: 1px solid #ddd; border-radius: 8px; text-align: center; cursor: pointer; transition: all 0.2s; background: white; }
        .time-slot:hover { background: #e8f5e9; border-color: #064e3b; }
        .time-slot.selected { background: #064e3b; color: white; border-color: #064e3b; }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-success text-white text-center py-3">
                    <h4 class="mb-0"><i class="fas fa-calendar-plus me-2"></i> Schedule Virtual Consultation</h4>
                </div>
                <div class="card-body p-4">
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?= $error ?></div>
                    <?php endif; ?>
                    
                    <form method="POST" id="scheduleForm">
                        <div class="mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-user me-2"></i>Select Patient</label>
                            <select name="patient_id" class="form-select" required>
                                <option value="">-- Choose Patient --</option>
                                <?php while($p = $patients->fetch_assoc()): ?>
                                    <option value="<?= $p['patient_id'] ?>">
                                        <?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?> 
                                        (<?= htmlspecialchars($p['email']) ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-calendar me-2"></i>Select Date & Time</label>
                            <input type="datetime-local" name="scheduled_time" id="scheduled_time" class="form-control" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-stethoscope me-2"></i>Reason for Consultation</label>
                            <input type="text" name="reason" class="form-control" placeholder="e.g., Follow-up, Symptoms check, etc.">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-notes-medical me-2"></i>Notes (Optional)</label>
                            <textarea name="notes" class="form-control" rows="3" placeholder="Any additional notes for the consultation..."></textarea>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            Once scheduled, the patient will receive a consultation link via email.
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="consultations.php" class="btn btn-outline-secondary me-md-2">Cancel</a>
                            <button type="submit" class="btn btn-primary">Schedule Consultation</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Quick Tips -->
            <div class="card mt-3">
                <div class="card-body">
                    <h6><i class="fas fa-lightbulb me-2"></i>Quick Tips</h6>
                    <ul class="small text-muted mb-0">
                        <li>Consultations use Jitsi Meet - a secure, HIPAA-compliant video platform</li>
                        <li>No download required - works in any browser</li>
                        <li>Patients receive a unique meeting link via email</li>
                        <li>You can start the consultation from your dashboard</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Set min datetime to now
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.getElementById('scheduled_time').min = now.toISOString().slice(0, 16);
</script>
</body>
</html>