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

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_availability') {
        // Clear existing then insert
        $conn->query("DELETE FROM doctor_availability WHERE doctor_id=$doctor_id");
        $days      = $_POST['days'] ?? [];
        $start     = clean($_POST['start_time'] ?? '09:00');
        $end       = clean($_POST['end_time'] ?? '17:00');
        $duration  = (int)($_POST['duration'] ?? 30);
        $max_slots = (int)($_POST['max_slots'] ?? 10);

        foreach ($days as $day) {
            $day = clean($day);
            $stmt = $conn->prepare("INSERT INTO doctor_availability (doctor_id,day_of_week,start_time,end_time,slot_duration,max_patients,is_available) VALUES (?,?,?,?,?,?,1)");
            $stmt->bind_param('isssis', $doctor_id, $day, $start, $end, $duration, $max_slots);
            $stmt->execute();
        }
        setFlash('success', 'Availability saved successfully.');
        header('Location: availability.php');
        exit;
    }

    if ($action === 'toggle_day') {
        $avail_id  = (int)$_POST['avail_id'];
        $current   = (int)$_POST['current_status'];
        $new_status = $current ? 0 : 1;
        $conn->query("UPDATE doctor_availability SET is_available=$new_status WHERE id=$avail_id AND doctor_id=$doctor_id");
        header('Location: availability.php');
        exit;
    }
}

// Fetch current availability
$availability = $conn->query("SELECT * FROM doctor_availability WHERE doctor_id=$doctor_id ORDER BY FIELD(day_of_week,'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')")->fetch_all(MYSQLI_ASSOC);
$saved_days = array_column($availability, 'day_of_week');
$all_days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$day_icons = ['Monday'=>'<i class="fas fa-calendar-day"></i>','Tuesday'=>'<i class="fas fa-calendar-day"></i>','Wednesday'=>'<i class="fas fa-calendar-day"></i>','Thursday'=>'<i class="fas fa-calendar-day"></i>','Friday'=>'<i class="fas fa-mosque"></i>','Saturday'=>'<i class="fas fa-calendar-day"></i>','Sunday'=>'<i class="fas fa-times-circle text-danger"></i>'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Availability - 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 { font-family: Inter, sans-serif; background: #f0f4ff; margin: 0; }
    .doc-body { padding: 20px 24px; }
    .doc-card { background:#fff; border:1px solid #e8edf8; border-radius:14px; overflow:hidden; box-shadow:0 2px 12px rgba(11,74,203,.07); }
    @media(max-width:768px) { .doc-body { padding: 12px; } }
  </style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<?php include 'topbar.php'; ?>
<div class="doc-main">
  <div class="doc-body">
    <?php displayFlash(); ?>

    <div class="row g-4">
      <!-- Set Availability Form -->
      <div class="col-lg-5">
        <div class="doc-card p-4">
          <h6 class="fw-700 mb-4"><i class="fas fa-cog me-2 text-primary"></i>Set Your Schedule</h6>
          <form method="POST">
            <input type="hidden" name="action" value="save_availability">
            <div class="mb-3">
              <label class="form-label fw-600">Available Days</label>
              <div class="row g-2">
                <?php foreach ($all_days as $day): ?>
                  <div class="col-6">
                    <div class="form-check" style="background:#f7fafa;padding:8px 12px 8px 34px;border-radius:8px;border:1px solid #e2e8f0;">
                      <input class="form-check-input" type="checkbox" name="days[]" value="<?= $day ?>" id="day_<?= $day ?>" <?= in_array($day,$saved_days)?'checked':'' ?>>
                      <label class="form-check-label fw-600" for="day_<?= $day ?>" style="font-size:0.85rem;"><?= $day_icons[$day] ?> <?= $day ?></label>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
            </div>
            <div class="row g-3">
              <div class="col-6">
                <label class="form-label fw-600">Start Time</label>
                <input type="time" name="start_time" class="form-control" value="<?= $availability[0]['start_time'] ?? '09:00' ?>">
              </div>
              <div class="col-6">
                <label class="form-label fw-600">End Time</label>
                <input type="time" name="end_time" class="form-control" value="<?= $availability[0]['end_time'] ?? '17:00' ?>">
              </div>
              <div class="col-6">
                <label class="form-label fw-600">Slot Duration (mins)</label>
                <select name="duration" class="form-select">
                  <?php foreach ([15,20,30,45,60] as $d): ?>
                    <option value="<?=$d?>" <?=($availability[0]['slot_duration']??30)==$d?'selected':''?>><?=$d?> minutes</option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="col-6">
                <label class="form-label fw-600">Max Patients/Day</label>
                <input type="number" name="max_slots" class="form-control" value="<?= $availability[0]['max_patients'] ?? 10 ?>" min="1" max="50">
              </div>
            </div>
            <button type="submit" class="btn btn-success w-100 mt-4"><i class="fas fa-save me-1"></i>Save Availability</button>
          </form>
        </div>
      </div>

      <!-- Current Schedule -->
      <div class="col-lg-7">
        <div class="doc-card">
          <div class="p-3 border-bottom"><h6 class="mb-0 fw-700"><i class="fas fa-calendar-alt me-2 text-primary"></i>Current Schedule</h6></div>
          <?php if (empty($availability)): ?>
            <div class="p-5 text-center text-muted">
              <i class="fas fa-calendar-times fa-3x mb-3" style="opacity:0.2;"></i>
              <h5>No schedule set</h5>
              <p>Set your availability using the form on the left.</p>
            </div>
          <?php else: ?>
            <?php foreach ($availability as $av): ?>
              <div class="d-flex align-items-center px-4 py-3" style="border-bottom:1px solid #f0f4f8;">
                <div style="width:130px;font-weight:700;font-size:0.9rem;"><?= $day_icons[$av['day_of_week']] ?> <?= $av['day_of_week'] ?></div>
                <div class="flex-grow-1">
                  <div style="font-size:0.82rem;color:#4a5568;">
                    <i class="fas fa-clock me-1"></i><?= date('h:i A', strtotime($av['start_time'])) ?> – <?= date('h:i A', strtotime($av['end_time'])) ?>
                    &nbsp;·&nbsp;<i class="fas fa-hourglass-half me-1"></i><?= $av['slot_duration'] ?> min slots
                    &nbsp;·&nbsp;<i class="fas fa-users me-1"></i>Max <?= $av['max_patients'] ?> patients
                  </div>
                </div>
                <form method="POST" style="display:inline;">
                  <input type="hidden" name="action" value="toggle_day">
                  <input type="hidden" name="avail_id" value="<?= $av['id'] ?>">
                  <input type="hidden" name="current_status" value="<?= $av['is_available'] ?>">
                  <button type="submit" class="btn btn-sm <?= $av['is_available'] ? 'btn-success' : 'btn-outline-danger' ?>">
                    <?= $av['is_available'] ? '<i class="fas fa-check me-1"></i>Available' : '<i class="fas fa-times me-1"></i>Off' ?>
                  </button>
                </form>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>