<?php
require_once '../config.php';
requirePatient();
$patient_id = $_SESSION['patient_id'];

$doctor_id = (int)($_GET['doctor_id'] ?? 0);
if (!$doctor_id) { header('Location: doctors.php'); exit; }

$stmt = $conn->prepare("SELECT d.*, s.name as specialization_name FROM doctors d LEFT JOIN specializations s ON d.specialization_id=s.id WHERE d.id=? AND d.verification_status='approved'");
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$doctor = $stmt->get_result()->fetch_assoc();
if (!$doctor) { setFlash('error','Doctor not found.'); header('Location: doctors.php'); exit; }

// Doctor availability
$availability = $conn->query("SELECT * FROM doctor_availability WHERE doctor_id=$doctor_id AND is_available=1")->fetch_all(MYSQLI_ASSOC);
$available_days = array_column($availability, 'day_of_week');

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $apt_date     = clean($_POST['appointment_date'] ?? '');
    $apt_time     = clean($_POST['appointment_time'] ?? '');
    $consult_type = clean($_POST['consultation_type'] ?? 'online');
    $symptoms     = clean($_POST['symptoms'] ?? '');
    $payment_method = clean($_POST['payment_method'] ?? 'cash');

    if (!$apt_date) $errors[] = 'Please select appointment date.';
    if (!$apt_time) $errors[] = 'Please select appointment time.';
    if (strtotime($apt_date) < strtotime('today')) $errors[] = 'Cannot select a past date.';

    // Check slot availability
    if (empty($errors)) {
        $check = $conn->prepare("SELECT id FROM appointments WHERE doctor_id=? AND appointment_date=? AND appointment_time=? AND status NOT IN('cancelled')");
        $check->bind_param('iss', $doctor_id, $apt_date, $apt_time);
        $check->execute();
        if ($check->get_result()->num_rows > 0) $errors[] = 'This slot is already booked. Please select another time.';
    }

    if (empty($errors)) {
        $apt_no  = generateAppointmentNo($conn);
        $fee     = $doctor['consultation_fee'];
        $pay_status = $payment_method === 'cash' ? 'pending' : 'paid';

        $stmt = $conn->prepare("INSERT INTO appointments (appointment_no,patient_id,doctor_id,appointment_date,appointment_time,consultation_type,symptoms,consultation_fee,payment_method,payment_status,status,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,'pending',NOW())");
        $stmt->bind_param('siissssdss', $apt_no, $patient_id, $doctor_id, $apt_date, $apt_time, $consult_type, $symptoms, $fee, $payment_method, $pay_status);

        if ($stmt->execute()) {
            $apt_id = $conn->insert_id;
            // Notify doctor
            $msg = "New appointment request from patient on $apt_date at $apt_time.";
            $conn->query("INSERT INTO notifications (user_type,user_id,title,message,type,channel,created_at) VALUES ('doctor',$doctor_id,'New Appointment Request','$msg','appointment','in_app',NOW())");

            setFlash('success', "Appointment booked! Reference: $apt_no");
            header('Location: appointments.php');
            exit;
        }
        $errors[] = 'Booking failed. Please try again.';
    }
}

// Generate time slots from doctor availability
$time_slots = [];
foreach ($availability as $av) {
    $start = strtotime($av['start_time']);
    $end   = strtotime($av['end_time']);
    $dur   = (int)($av['slot_duration'] ?? 30);
    for ($t = $start; $t < $end; $t += $dur * 60) {
        $time_slots[] = date('H:i:s', $t);
    }
}
if (empty($time_slots)) {
    $time_slots = ['09:00:00','09:30:00','10:00:00','10:30:00','11:00:00','11:30:00','14:00:00','14:30:00','15:00:00','15:30:00','16:00:00','16:30:00','17:00:00'];
}
$time_slots = array_unique($time_slots);
sort($time_slots);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Book Appointment - HealthLink</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body { background: #f0f4ff; font-family: Inter, 'Segoe UI', sans-serif; overflow-x:hidden; }
    .card { border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 2px 10px rgba(11,74,203,.07); }
    .page-body { padding: 20px 24px; }
    @media(max-width:768px){ .page-body{ padding:12px; } }
    .time-slot { padding: 8px 14px; border: 1.5px solid #e2e8f0; border-radius: 8px; cursor: pointer; font-size: 0.82rem; font-weight: 600; transition: all 0.2s; text-align: center; }
    .time-slot:hover, .time-slot.selected { background: #0B7B6E; color: white; border-color: #0B7B6E; }
    .time-slot.booked { background: #f0f0f0; color: #aaa; cursor: not-allowed; border-style: dashed; }
    .payment-option { border: 2px solid #e2e8f0; border-radius: 10px; padding: 12px; cursor: pointer; transition: all 0.2s; }
    .payment-option:has(input:checked), .payment-option.selected { border-color: #0B7B6E; background: #e6f5f3; }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main-content">
<?php $page_title = 'Book Appointment'; include 'topbar.php'; ?>
  <div class="page-body">
    <?php if (!empty($errors)): ?>
      <div class="alert alert-danger"><ul class="mb-0"><?php foreach($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul></div>
    <?php endif; ?>

    <div class="row g-4">
      <!-- Doctor Info -->
      <div class="col-lg-4">
        <div class="card p-4 text-center">
          <?php if ($doctor['profile_photo']): ?>
            <img src="<?= SITE_URL ?>/<?= $doctor['profile_photo'] ?>" style="width:90px;height:90px;border-radius:50%;object-fit:cover;margin:0 auto 12px;" alt="">
          <?php else: ?>
            <div style="width:90px;height:90px;border-radius:50%;background:#e6f5f3;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;">
              <i class="fas fa-user-md" style="font-size:2.5rem;color:#0B7B6E;"></i>
            </div>
          <?php endif; ?>
          <h5 class="fw-800 mb-1">Dr. <?= htmlspecialchars($doctor['full_name']) ?></h5>
          <div style="color:#0B7B6E;font-size:0.85rem;font-weight:600;"><?= htmlspecialchars($doctor['specialization_name']) ?></div>
          <div style="font-size:0.78rem;color:#718096;"><?= htmlspecialchars($doctor['qualification']) ?> &middot; <?= $doctor['experience_years'] ?> yrs</div>

          <div style="background:#e6f5f3;border-radius:12px;padding:16px;margin-top:16px;">
            <div style="font-size:0.72rem;color:#718096;font-weight:700;text-transform:uppercase;">Consultation Fee</div>
            <div style="font-size:1.8rem;font-weight:800;color:#0B7B6E;">Rs. <?= number_format($doctor['consultation_fee']) ?></div>
          </div>

          <?php if (!empty($available_days)): ?>
            <div class="mt-3">
              <div style="font-size:0.72rem;color:#718096;font-weight:700;text-transform:uppercase;margin-bottom:8px;">Available Days</div>
              <div class="d-flex flex-wrap gap-1 justify-content-center">
                <?php foreach ($available_days as $day): ?>
                  <span style="background:#f7fafa;border:1px solid #e2e8f0;border-radius:20px;padding:3px 10px;font-size:0.72rem;font-weight:600;"><?= $day ?></span>
                <?php endforeach; ?>
              </div>
            </div>
          <?php endif; ?>

          <?php if ($doctor['clinic_name']): ?>
            <div class="mt-3 text-start" style="font-size:0.78rem;background:#f7fafa;padding:10px;border-radius:8px;">
              <i class="fas fa-hospital text-success me-1"></i><strong><?= htmlspecialchars($doctor['clinic_name']) ?></strong><br>
              <i class="fas fa-map-marker-alt text-danger me-1"></i><?= htmlspecialchars($doctor['clinic_address'] ?? $doctor['city']) ?>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Booking Form -->
      <div class="col-lg-8">
        <div class="card p-4">
          <form method="POST">
            <!-- Date & Type -->
            <div class="row g-3 mb-4">
              <div class="col-md-6">
                <label class="form-label fw-600">Appointment Date *</label>
                <input type="date" name="appointment_date" class="form-control" min="<?= date('Y-m-d') ?>" value="<?= $_POST['appointment_date'] ?? '' ?>" required>
              </div>
              <div class="col-md-6">
                <label class="form-label fw-600">Consultation Type *</label>
                <div class="d-flex gap-2">
                  <label style="flex:1;">
                    <div class="payment-option text-center">
                      <input type="radio" name="consultation_type" value="online" <?= ($_POST['consultation_type']??'online')==='online'?'checked':'' ?> hidden>
                      <i class="fas fa-video" style="font-size:1.4rem;color:#0B4ACB;"></i>
                      <div style="font-size:0.78rem;font-weight:600;">Online</div>
                    </div>
                  </label>
                  <label style="flex:1;">
                    <div class="payment-option text-center">
                      <input type="radio" name="consultation_type" value="physical" <?= ($_POST['consultation_type']??'')==='physical'?'checked':'' ?> hidden>
                      <i class="fas fa-hospital" style="font-size:1.4rem;color:#0B4ACB;"></i>
                      <div style="font-size:0.78rem;font-weight:600;">Physical</div>
                    </div>
                  </label>
                </div>
              </div>
            </div>

            <!-- Time Slots -->
            <div class="mb-4">
              <label class="form-label fw-600">Select Time Slot *</label>
              <div class="row g-2" id="timeSlots">
                <?php foreach ($time_slots as $slot): ?>
                  <div class="col-3 col-md-2">
                    <label>
                      <input type="radio" name="appointment_time" value="<?= $slot ?>" hidden required>
                      <div class="time-slot"><?= date('h:i A', strtotime($slot)) ?></div>
                    </label>
                  </div>
                <?php endforeach; ?>
              </div>
            </div>

            <!-- Symptoms -->
            <div class="mb-4">
              <label class="form-label fw-600">Symptoms / Reason for Visit</label>
              <textarea name="symptoms" class="form-control" rows="3" placeholder="Describe your symptoms or reason for consultation..."><?= htmlspecialchars($_POST['symptoms'] ?? '') ?></textarea>
            </div>

            <!-- Payment Method -->
            <div class="mb-4">
              <label class="form-label fw-600">Payment Method</label>
              <div class="row g-2">
                <?php $payments = [
                  ['cash',      'fa-money-bill-wave', 'Pay at Clinic'],
                  ['card',      'fa-credit-card',     'Credit/Debit Card'],
                  ['easypaisa', 'fa-mobile-alt',      'EasyPaisa'],
                  ['jazzcash',  'fa-mobile-alt',      'JazzCash'],
                  ['bank',      'fa-university',      'Bank Transfer'],
                ]; ?>
                <?php foreach ($payments as [$val,$icon,$label]): ?>
                  <div class="col-6 col-md-4">
                    <label>
                      <div class="payment-option text-center">
                        <input type="radio" name="payment_method" value="<?= $val ?>" <?= ($_POST['payment_method']??'cash')===$val?'checked':'' ?> hidden>
                        <i class="fas <?= $icon ?>" style="font-size:1.3rem;color:#0B4ACB;"></i>
                        <div style="font-size:0.75rem;font-weight:600;"><?= $label ?></div>
                      </div>
                    </label>
                  </div>
                <?php endforeach; ?>
              </div>
            </div>

            <!-- Summary -->
            <div style="background:#f0fff4;border:1px solid #0B7B6E;border-radius:12px;padding:16px;margin-bottom:20px;">
              <div class="d-flex justify-content-between mb-1">
                <span style="font-size:0.85rem;">Consultation Fee</span>
                <strong>Rs. <?= number_format($doctor['consultation_fee']) ?></strong>
              </div>
              <div class="d-flex justify-content-between">
                <span style="font-size:0.85rem;">Platform Fee</span>
                <strong>Rs. 0</strong>
              </div>
              <hr class="my-2">
              <div class="d-flex justify-content-between">
                <strong>Total</strong>
                <strong style="color:#0B7B6E;font-size:1rem;">Rs. <?= number_format($doctor['consultation_fee']) ?></strong>
              </div>
            </div>

            <button type="submit" class="btn btn-success w-100 btn-lg">
              <i class="fas fa-calendar-check me-2"></i>Confirm Booking
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Highlight selected time slot and payment method
  document.querySelectorAll('input[type=radio]').forEach(radio => {
    radio.addEventListener('change', () => {
      const name = radio.getAttribute('name');
      document.querySelectorAll(`input[name="${name}"]`).forEach(r => {
        r.closest('label')?.querySelector('.time-slot, .payment-option')?.classList.remove('selected');
      });
      radio.closest('label')?.querySelector('.time-slot, .payment-option')?.classList.add('selected');
    });
  });
  // Init selected state
  document.querySelectorAll('input[type=radio]:checked').forEach(r => {
    r.closest('label')?.querySelector('.time-slot, .payment-option')?.classList.add('selected');
  });
</script>
</body>
</html>
