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

$db     = getDB();
$lid    = $_SESSION['lawyer_id'];
$lawyer = getCurrentLawyer();

// Filters
$statusFilter = sanitize($_GET['status'] ?? '');
$dateFilter   = sanitize($_GET['date'] ?? '');
$page         = max(1, (int)($_GET['page'] ?? 1));
$perPage      = 12;

$where  = ["a.lawyer_id = ?"];
$params = [$lid];

if ($statusFilter && in_array($statusFilter, ['pending','confirmed','completed','cancelled','rejected'])) {
    $where[]  = "a.status = ?";
    $params[] = $statusFilter;
}
if ($dateFilter) {
    $where[]  = "a.appointment_date = ?";
    $params[] = $dateFilter;
}

$whereSQL = implode(' AND ', $where);

$totalStmt = $db->prepare("SELECT COUNT(*) FROM appointments a WHERE $whereSQL");
$totalStmt->execute($params);
$total      = (int)$totalStmt->fetchColumn();
$totalPages = max(1, ceil($total / $perPage));
$offset     = ($page - 1) * $perPage;

$stmt = $db->prepare("
    SELECT a.*, u.name AS client_name, u.email AS client_email, u.mobile AS client_mobile
    FROM appointments a
    JOIN users u ON a.user_id = u.id
    WHERE $whereSQL
    ORDER BY a.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$appointments = $stmt->fetchAll();

// Count by status for tabs
$counts = [];
foreach (['pending','confirmed','completed','cancelled','rejected'] as $s) {
    $cs = $db->prepare("SELECT COUNT(*) FROM appointments WHERE lawyer_id=? AND status=?");
    $cs->execute([$lid, $s]);
    $counts[$s] = (int)$cs->fetchColumn();
}
$counts['all'] = array_sum($counts);

// ── Inline dashboard layout (same style as dashboard.php) ──
$pageTitle = 'My Appointments — meevakeel';

function statusBadge(string $status): string {
    $map = [
        'pending'   => ['bg'=>'rgba(255,193,7,.15)',    'color'=>'#b8860b',   'label'=>'Pending'],
        'confirmed' => ['bg'=>'rgba(40,167,69,.12)',    'color'=>'#1a7a34',   'label'=>'Confirmed'],
        'completed' => ['bg'=>'rgba(10,35,66,.1)',      'color'=>'#0A2342',   'label'=>'Completed'],
        'cancelled' => ['bg'=>'rgba(220,53,69,.1)',     'color'=>'#c0392b',   'label'=>'Cancelled'],
        'rejected'  => ['bg'=>'rgba(220,53,69,.1)',     'color'=>'#c0392b',   'label'=>'Rejected'],
        'ongoing'   => ['bg'=>'rgba(23,162,184,.12)',   'color'=>'#0c7590',   'label'=>'Ongoing'],
    ];
    $s = $map[$status] ?? ['bg'=>'rgba(0,0,0,.06)','color'=>'#555','label'=>ucfirst($status)];
    return "<span style='background:{$s['bg']};color:{$s['color']};padding:4px 12px;border-radius:50px;font-size:.72rem;font-weight:700;'>{$s['label']}</span>";
}
?>
<!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;}
.status-tab{padding:8px 18px;border-radius:50px;font-size:.8rem;font-weight:600;text-decoration:none;border:1px solid var(--border);color:var(--text-light);background:white;transition:all .3s;white-space:nowrap;}
.status-tab.active{background:var(--primary);color:white;border-color:var(--primary);}
.appt-row{background:white;border-radius:12px;padding:18px 20px;border:1px solid var(--border);margin-bottom:12px;transition:all .3s;}
.appt-row:hover{border-color:var(--gold);box-shadow:var(--shadow);}
@media(max-width:768px){.dash-sidebar{display:none;}.dash-main{margin-left:0;}}
</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);font-family:var(--font-heading);">
      <?= 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 active">
    <i class="fas fa-calendar-check"></i> Appointments
  </a>

  <a href="<?= SITE_URL ?>/lawyer/availability.php" class="dash-nav-link">
    <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>

<!-- Main content -->
<div class="dash-main">
  <div class="dash-topbar">
    <div>
      <h5 style="margin:0;font-size:1rem;color:var(--primary);">Appointments</h5>
      <span style="font-size:.78rem;color:var(--text-light);">Manage your consultations</span>
    </div>
    <a href="/lawyer/logout.php" style="color:var(--text-light);font-size:.82rem;">Logout</a>
  </div>

  <div class="dash-content">

    <!-- Status tab pills -->
    <div style="display:flex;gap:8px;overflow-x:auto;margin-bottom:24px;padding-bottom:4px;">
      <a href="?" class="status-tab <?= !$statusFilter?'active':'' ?>">
        All <span style="opacity:.65;">(<?= $counts['all'] ?>)</span>
      </a>
      <?php foreach (['pending'=>'⏳','confirmed'=>'✅','completed'=>'🏁','cancelled'=>'❌','rejected'=>'🚫'] as $s=>$emoji): ?>
      <a href="?status=<?= $s ?>" class="status-tab <?= $statusFilter===$s?'active':'' ?>">
        <?= $emoji ?> <?= ucfirst($s) ?> <span style="opacity:.65;">(<?= $counts[$s] ?>)</span>
      </a>
      <?php endforeach; ?>
    </div>

    <!-- Date filter -->
    <div style="display:flex;gap:12px;align-items:center;margin-bottom:22px;flex-wrap:wrap;">
      <form method="GET" style="display:flex;gap:8px;align-items:center;">
        <?php if ($statusFilter): ?><input type="hidden" name="status" value="<?= $statusFilter ?>"><?php endif; ?>
        <label style="font-size:.82rem;font-weight:600;color:var(--text-light);">Filter by date:</label>
        <input type="date" name="date" value="<?= htmlspecialchars($dateFilter) ?>" class="form-control"
               style="width:160px;font-size:.85rem;border-radius:8px;">
        <button type="submit" class="btn btn-gold" style="padding:8px 18px;font-size:.82rem;border-radius:8px;">Filter</button>
        <?php if ($dateFilter): ?>
        <a href="?<?= $statusFilter?'status='.$statusFilter:'' ?>" style="font-size:.82rem;color:var(--primary);">Clear date</a>
        <?php endif; ?>
      </form>
      <span style="font-size:.82rem;color:var(--text-light);margin-left:auto;"><?= $total ?> appointment<?= $total!=1?'s':'' ?> found</span>
    </div>

    <?php if (empty($appointments)): ?>
    <div style="background:white;border-radius:16px;padding:60px;text-align:center;border:1px solid var(--border);">
      <i class="fas fa-calendar-times" style="font-size:3rem;color:var(--border);margin-bottom:16px;display:block;"></i>
      <h5 style="color:var(--primary);">No appointments found</h5>
      <p style="color:var(--text-light);font-size:.88rem;">
        <?= $statusFilter ? "No $statusFilter appointments." : "You don't have any appointments yet." ?>
      </p>
    </div>
    <?php else: ?>

    <!-- Appointment cards -->
    <?php foreach ($appointments as $a): ?>
    <div class="appt-row">
      <div class="row align-items-center g-3">

        <!-- Client info -->
        <div class="col-md-3">
          <div style="display:flex;align-items:center;gap:12px;">
            <div style="width:42px;height:42px;min-width:42px;background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:50%;display:flex;align-items:center;justify-content:center;color:var(--gold);font-weight:800;font-size:.9rem;">
              <?= strtoupper(substr($a['client_name'],0,1)) ?>
            </div>
            <div>
              <div style="font-weight:700;font-size:.88rem;color:var(--primary);"><?= htmlspecialchars($a['client_name']) ?></div>
              <div style="font-size:.72rem;color:var(--text-light);"><?= $a['client_mobile'] ?></div>
              <div style="font-size:.7rem;color:var(--text-light);word-break:break-all;"><?= $a['client_email'] ?></div>
            </div>
          </div>
        </div>

        <!-- Booking details -->
        <div class="col-md-3">
          <div style="font-size:.72rem;font-weight:700;color:var(--text-light);text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px;">Booking ID</div>
          <div style="font-size:.82rem;font-weight:700;color:var(--primary);"><?= $a['booking_id'] ?></div>
          <div style="margin-top:5px;">
            <span style="background:rgba(10,35,66,.07);color:var(--primary);padding:3px 10px;border-radius:50px;font-size:.72rem;font-weight:600;text-transform:capitalize;">
              <?= str_replace('_',' ',$a['consultation_type']) ?>
            </span>
          </div>
        </div>

        <!-- Date & time -->
        <div class="col-md-2">
          <div style="font-size:.72rem;font-weight:700;color:var(--text-light);text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px;">Date & Time</div>
          <?php if ($a['appointment_date']): ?>
          <div style="font-size:.88rem;font-weight:600;color:var(--primary);"><?= date('d M Y', strtotime($a['appointment_date'])) ?></div>
          <?php if ($a['appointment_time']): ?>
          <div style="font-size:.78rem;color:var(--text-light);"><?= date('h:i A', strtotime($a['appointment_time'])) ?></div>
          <?php endif; ?>
          <?php else: ?>
          <div style="font-size:.8rem;color:var(--text-light);">Not set</div>
          <?php endif; ?>
          <div style="font-size:.72rem;color:var(--text-light);margin-top:3px;">Booked <?= date('d M', strtotime($a['created_at'])) ?></div>
        </div>

        <!-- Issue -->
        <div class="col-md-2">
          <div style="font-size:.72rem;font-weight:700;color:var(--text-light);text-transform:uppercase;letter-spacing:.05em;margin-bottom:3px;">Issue</div>
          <div style="font-size:.8rem;color:var(--text-light);line-height:1.5;">
            <?= htmlspecialchars(mb_strimwidth($a['description'] ?? '—', 0, 60, '...')) ?>
          </div>
        </div>

        <!-- Status + Actions -->
        <div class="col-md-2">
          <div style="margin-bottom:10px;"><?= statusBadge($a['status']) ?></div>
          <?php if ($a['status'] === 'pending'): ?>
          <div style="display:flex;flex-direction:column;gap:6px;">
            <a href="/lawyer/update-appointment.php?id=<?= $a['id'] ?>&action=confirm"
               style="background:rgba(40,167,69,.1);color:#1a7a34;padding:6px 14px;border-radius:8px;font-size:.75rem;font-weight:700;text-decoration:none;text-align:center;border:1px solid rgba(40,167,69,.2);">
               <i class="fas fa-check me-1"></i>Confirm
            </a>
            <a href="/lawyer/update-appointment.php?id=<?= $a['id'] ?>&action=reject"
               style="background:rgba(220,53,69,.07);color:#c0392b;padding:6px 14px;border-radius:8px;font-size:.75rem;font-weight:700;text-decoration:none;text-align:center;border:1px solid rgba(220,53,69,.2);"
               onclick="return confirm('Reject this appointment?')">
               <i class="fas fa-times me-1"></i>Reject
            </a>
          </div>
          <?php elseif ($a['status'] === 'confirmed'): ?>
          <a href="/lawyer/update-appointment.php?id=<?= $a['id'] ?>&action=complete"
             style="background:rgba(10,35,66,.08);color:var(--primary);padding:6px 14px;border-radius:8px;font-size:.75rem;font-weight:700;text-decoration:none;text-align:center;display:block;border:1px solid var(--border);">
             <i class="fas fa-check-double me-1"></i>Mark Done
          </a>
          <?php endif; ?>
        </div>

      </div>
    </div>
    <?php endforeach; ?>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav style="margin-top:28px;">
      <ul class="pagination justify-content-center gap-1">
        <?php for ($p = 1; $p <= $totalPages; $p++): ?>
        <li class="page-item">
          <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>"
             style="border-radius:10px;<?= $p===$page?'background:var(--primary);border-color:var(--primary);color:white;':'border:1px solid var(--border);color:var(--primary);' ?>padding:9px 15px;">
            <?= $p ?>
          </a>
        </li>
        <?php endfor; ?>
      </ul>
    </nav>
    <?php endif; ?>

    <?php endif; ?>
  </div><!-- /dash-content -->
</div><!-- /dash-main -->

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