<?php
// meevakeel/lawyer/availability.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
requireLawyerLogin();

$db     = getDB();
$lid    = $_SESSION['lawyer_id'];
$lawyer = getCurrentLawyer();
$days   = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];

$success = $error = '';

// ── Handle Save ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_availability'])) {
    if (!validateCSRF($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        // Delete existing slots for this lawyer
        $db->prepare("DELETE FROM lawyer_availability WHERE lawyer_id = ?")->execute([$lid]);

        $ins = $db->prepare("INSERT INTO lawyer_availability (lawyer_id, day_of_week, start_time, end_time, is_available) VALUES (?,?,?,?,1)");

        foreach ($days as $day) {
            $key = strtolower($day);
            if (!empty($_POST["day_$key"])) {          // checkbox ticked
                $start = $_POST["start_$key"] ?? '09:00';
                $end   = $_POST["end_$key"]   ?? '18:00';
                if ($start && $end && $start < $end) {
                    $ins->execute([$lid, $day, $start, $end]);
                }
            }
        }

        // Update consultation fee if submitted
        if (isset($_POST['consultation_fee']) && $lawyer['experience_years'] !== '2-4') {
            $fee = max(0, (float)$_POST['consultation_fee']);
            $db->prepare("UPDATE lawyers SET consultation_fee = ? WHERE id = ?")->execute([$fee, $lid]);
        }

        $success = 'Availability saved successfully!';
        // Reload lawyer data
        $lawyer = getCurrentLawyer();
    }
}

// ── Load existing slots ──────────────────────────────────────
$slotStmt = $db->prepare("SELECT * FROM lawyer_availability WHERE lawyer_id = ?");
$slotStmt->execute([$lid]);
$existingSlots = [];
foreach ($slotStmt->fetchAll() as $s) {
    $existingSlots[strtolower($s['day_of_week'])] = $s;
}

$pageTitle = 'Availability Settings — MeeVakeel';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;800&family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/meevakeel/assets/css/style.css">
<style>
body{background:var(--off-white);font-family:var(--font-body);}
.dash-sidebar{width:240px;min-height:100vh;background:var(--primary-dark);position:fixed;top:0;left:0;z-index:200;overflow-y:auto;}
.dash-main{margin-left:240px;min-height:100vh;}
.dash-topbar{background:white;padding:14px 28px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100;box-shadow:0 2px 8px rgba(0,0,0,.05);}
.dash-content{padding:28px;}
.dash-nav-link{display:flex;align-items:center;gap:12px;padding:11px 20px;color:rgba(255,255,255,.65);font-size:.87rem;font-weight:500;border-radius:8px;margin:2px 10px;text-decoration:none;transition:all .3s;}
.dash-nav-link:hover,.dash-nav-link.active{background:rgba(212,175,55,.15);color:var(--gold);}
.dash-nav-link i{width:18px;text-align:center;}
.nav-section-label{font-size:.68rem;color:rgba(255,255,255,.3);font-weight:700;letter-spacing:.1em;text-transform:uppercase;padding:16px 20px 6px;}
.day-row{background:white;border-radius:14px;padding:18px 22px;border:1px solid var(--border);margin-bottom:12px;transition:all .3s;}
.day-row.active-day{border-color:var(--gold);background:rgba(212,175,55,.04);}
.day-check{width:20px;height:20px;accent-color:var(--primary);cursor:pointer;}
.time-input{border:1.5px solid var(--border);border-radius:8px;padding:9px 12px;font-size:.88rem;width:120px;}
.time-input:focus{outline:none;border-color:var(--primary);}
@media(max-width:768px){.dash-sidebar{display:none;}.dash-main{margin-left:0;}.time-input{width:100%;}}
</style>
</head>
<body>

<!-- Sidebar -->
<div class="dash-sidebar">
  <div style="padding:22px 20px;border-bottom:1px solid rgba(255,255,255,.08);">
    <div style="font-family:var(--font-heading);font-size:1.3rem;font-weight:800;color:white;"><span style="color:var(--gold);">Nyaya</span> Guru</div>
    <div style="font-size:.72rem;color:rgba(255,255,255,.4);margin-top:2px;">Lawyer Portal</div>
  </div>
  <div style="padding:18px 20px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;align-items:center;gap:12px;">
    <div style="width:40px;height:40px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;color:var(--primary);"><?= strtoupper(substr($lawyer['name'],0,1)) ?></div>
    <div>
      <div style="color:white;font-size:.85rem;font-weight:600;"><?= htmlspecialchars(explode(' ',$lawyer['name'])[0]) ?></div>
      <div style="font-size:.7rem;color:rgba(255,193,7,.8);">⏳ <?= ucfirst($lawyer['verification_status']) ?></div>
    </div>
  </div>
  <div class="nav-section-label">Main</div>
 <a href="<?= SITE_URL ?>/lawyer/dashboard.php" class="dash-nav-link">
    <i class="fas fa-tachometer-alt"></i> Dashboard
</a>

<a href="<?= SITE_URL ?>/lawyer/appointments.php" class="dash-nav-link">
    <i class="fas fa-calendar-check"></i> Appointments
</a>

<a href="<?= SITE_URL ?>/lawyer/availability.php" class="dash-nav-link active">
    <i class="fas fa-clock"></i> Availability
</a>

<div class="nav-section-label">Account</div>

<a href="<?= SITE_URL ?>/lawyer/profile.php" class="dash-nav-link">
    <i class="fas fa-user-edit"></i> My Profile
</a>

<a href="<?= SITE_URL ?>/lawyer/logout.php" class="dash-nav-link" style="color:rgba(220,53,69,.8);">
    <i class="fas fa-sign-out-alt"></i> Logout
</a>
</div>

<div class="dash-main">
  <div class="dash-topbar">
    <div>
      <h5 style="margin:0;font-size:1rem;color:var(--primary);">Availability Settings</h5>
      <span style="font-size:.78rem;color:var(--text-light);">Set your working days and hours</span>
    </div>
    <a href="/lawyer/logout.php" style="color:var(--text-light);font-size:.82rem;">Logout</a>
  </div>

  <div class="dash-content">

    <?php if ($success): ?>
    <div style="background:rgba(40,167,69,.08);border:1px solid rgba(40,167,69,.3);border-radius:12px;padding:14px 18px;margin-bottom:22px;color:#1a7a34;font-size:.88rem;">
      <i class="fas fa-check-circle me-2"></i><?= $success ?>
    </div>
    <?php endif; ?>
    <?php if ($error): ?>
    <div style="background:rgba(220,53,69,.07);border:1px solid rgba(220,53,69,.25);border-radius:12px;padding:14px 18px;margin-bottom:22px;color:#c0392b;font-size:.88rem;">
      <i class="fas fa-exclamation-circle me-2"></i><?= $error ?>
    </div>
    <?php endif; ?>

    <div class="row g-4">

      <!-- Availability form -->
      <div class="col-lg-8">
        <div style="background:white;border-radius:16px;padding:28px;box-shadow:var(--shadow);border:1px solid var(--border);">
          <h5 style="color:var(--primary);font-size:1rem;margin-bottom:6px;"><i class="fas fa-calendar-week me-2" style="color:var(--gold);"></i>Weekly Schedule</h5>
          <p style="color:var(--text-light);font-size:.82rem;margin-bottom:24px;">Check a day to mark yourself available. Set your working hours for each day.</p>

          <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= generateCSRF() ?>">
            <input type="hidden" name="save_availability" value="1">

            <?php foreach ($days as $day):
              $key     = strtolower($day);
              $slot    = $existingSlots[$key] ?? null;
              $checked = $slot ? 'checked' : '';
              $start   = $slot['start_time'] ?? '09:00';
              $end     = $slot['end_time']   ?? '18:00';
              // Format time for input (HH:MM)
              $startFmt = substr($start, 0, 5);
              $endFmt   = substr($end,   0, 5);
              $isWeekend = in_array($day, ['Saturday','Sunday']);
            ?>
            <div class="day-row <?= $slot ? 'active-day' : '' ?>" id="row_<?= $key ?>">
              <div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
                <!-- Checkbox -->
                <label style="display:flex;align-items:center;gap:10px;cursor:pointer;min-width:130px;">
                  <input type="checkbox" name="day_<?= $key ?>" id="day_<?= $key ?>" class="day-check"
                         <?= $checked ?>
                         onchange="toggleDay('<?= $key ?>')">
                  <span style="font-weight:700;font-size:.92rem;color:var(--primary);">
                    <?= $day ?>
                    <?php if ($isWeekend): ?>
                    <span style="font-size:.7rem;color:var(--gold);font-weight:600;margin-left:4px;">Weekend</span>
                    <?php endif; ?>
                  </span>
                </label>

                <!-- Time range -->
                <div id="times_<?= $key ?>" style="display:flex;align-items:center;gap:10px;<?= !$slot ? 'opacity:.35;pointer-events:none;' : '' ?> flex-wrap:wrap;">
                  <span style="font-size:.78rem;color:var(--text-light);font-weight:600;">From</span>
                  <input type="time" name="start_<?= $key ?>" value="<?= $startFmt ?>" class="time-input">
                  <span style="font-size:.78rem;color:var(--text-light);font-weight:600;">To</span>
                  <input type="time" name="end_<?= $key ?>" value="<?= $endFmt ?>" class="time-input">
                  <span style="font-size:.75rem;color:var(--text-light);">
                    <?php
                    if ($slot) {
                        $diff = (strtotime($end) - strtotime($start)) / 3600;
                        echo number_format($diff, 1).' hrs';
                    }
                    ?>
                  </span>
                </div>

                <!-- Unavailable badge -->
                <?php if (!$slot): ?>
                <span style="margin-left:auto;background:var(--off-white);color:var(--text-light);padding:4px 12px;border-radius:50px;font-size:.72rem;font-weight:600;">Not Available</span>
                <?php else: ?>
                <span style="margin-left:auto;background:rgba(40,167,69,.1);color:#1a7a34;padding:4px 12px;border-radius:50px;font-size:.72rem;font-weight:600;"><i class="fas fa-check me-1"></i>Available</span>
                <?php endif; ?>
              </div>
            </div>
            <?php endforeach; ?>

            <!-- Consultation fee (if 5+ yrs experience) -->
            <?php if ($lawyer['experience_years'] !== '2-4'): ?>
            <div style="background:var(--off-white);border-radius:12px;padding:18px 20px;border:1px solid var(--border);margin-top:20px;">
              <label style="font-weight:700;font-size:.88rem;color:var(--primary);display:block;margin-bottom:10px;">
                <i class="fas fa-rupee-sign me-2" style="color:var(--gold);"></i>Consultation Fee (₹ per 30-min session)
              </label>
              <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
                <input type="number" name="consultation_fee" class="form-control"
                       value="<?= (int)$lawyer['consultation_fee'] ?>"
                       min="0" max="50000" step="50"
                       style="width:160px;border-radius:8px;font-weight:700;font-size:1rem;">
                <span style="font-size:.82rem;color:var(--text-light);">Platform takes 20% commission. You receive <?= 100 - 20 ?>%.</span>
              </div>
            </div>
            <?php else: ?>
            <div style="background:rgba(40,167,69,.07);border:1px solid rgba(40,167,69,.2);border-radius:12px;padding:14px 18px;margin-top:20px;">
              <i class="fas fa-info-circle me-2" style="color:#1a7a34;"></i>
              <span style="font-size:.85rem;color:#1a7a34;font-weight:600;">As a 2–4 year experience lawyer, your first 10-minute consultation is free (mandatory).</span>
            </div>
            <?php endif; ?>

            <button type="submit" class="btn btn-gold mt-4 px-5 py-3" style="font-weight:700;border-radius:12px;">
              <i class="fas fa-save me-2"></i>Save Availability
            </button>
          </form>
        </div>
      </div>

      <!-- Summary sidebar -->
      <div class="col-lg-4">
        <div style="background:white;border-radius:16px;padding:24px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:18px;">
          <h6 style="color:var(--primary);font-size:.88rem;font-weight:800;margin-bottom:16px;text-transform:uppercase;letter-spacing:.05em;">Current Schedule</h6>
          <?php if (empty($existingSlots)): ?>
          <p style="color:var(--text-light);font-size:.82rem;">No availability set. Clients won't be able to book you.</p>
          <?php else: ?>
            <?php foreach ($days as $day):
              $key  = strtolower($day);
              $slot = $existingSlots[$key] ?? null;
            ?>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border);">
              <span style="font-size:.83rem;font-weight:600;color:var(--primary);"><?= $day ?></span>
              <?php if ($slot): ?>
              <span style="font-size:.78rem;color:#1a7a34;font-weight:600;">
                <?= date('g:i A', strtotime($slot['start_time'])) ?> – <?= date('g:i A', strtotime($slot['end_time'])) ?>
              </span>
              <?php else: ?>
              <span style="font-size:.75rem;color:var(--text-light);">—</span>
              <?php endif; ?>
            </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>

        <div style="background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:16px;padding:22px;">
          <h6 style="color:var(--gold);font-size:.85rem;margin-bottom:12px;"><i class="fas fa-lightbulb me-2"></i>Tips</h6>
          <ul style="color:rgba(255,255,255,.7);font-size:.78rem;line-height:1.8;padding-left:16px;margin:0;">
            <li>Set at least 3–4 available days to attract more clients.</li>
            <li>Weekday mornings (9 AM–12 PM) are peak booking times.</li>
            <li>Keep your fee competitive for your experience level.</li>
            <li>Update your schedule regularly to avoid conflicts.</li>
          </ul>
        </div>
      </div>

    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleDay(key) {
  var cb    = document.getElementById('day_' + key);
  var times = document.getElementById('times_' + key);
  var row   = document.getElementById('row_' + key);
  if (cb.checked) {
    times.style.opacity       = '1';
    times.style.pointerEvents = 'auto';
    row.classList.add('active-day');
  } else {
    times.style.opacity       = '0.35';
    times.style.pointerEvents = 'none';
    row.classList.remove('active-day');
  }
}
</script>
</body>
</html>