<?php
// nyaya-guru/lawyers.php — Find Lawyers
require_once __DIR__ . '/includes/config.php';

$db         = getDB();
$categories = $db->query("SELECT * FROM legal_categories WHERE status=1 ORDER BY name")->fetchAll();
$states     = $db->query("SELECT * FROM states WHERE status=1 ORDER BY name")->fetchAll();

// ── Filters ──────────────────────────────────────
$categoryId = (int)($_GET['category'] ?? 0);
$stateId  = (int)($_GET['state'] ?? 0);
$city = sanitize($_GET['city'] ?? '');
$exp      = sanitize($_GET['experience'] ?? '');
$lang     = sanitize($_GET['language'] ?? '');
$search   = sanitize($_GET['q'] ?? '');
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 9;

// ── Build Query ───────────────────────────────────
$where  = ["l.status = 1"];
$params = [];

if ($categoryId > 0) {
    $where[]  = "lc.id = ?";
    $params[] = $categoryId;
}
if ($stateId) { $where[] = "l.state_id = ?"; $params[] = $stateId; }
if ($city) {

    if (is_numeric($city)) {

        $where[] = "l.city_id = ?";
        $params[] = (int)$city;

    } else {

        $where[] = "c.name LIKE ?";
        $params[] = $city;
    }
}
if ($exp && in_array($exp, ['2-4','5-10','10+'])) { $where[] = "l.experience_years = ?"; $params[] = $exp; }
if ($lang)    { $where[] = "l.languages LIKE ?"; $params[] = "%$lang%"; }
if ($search)  { $where[] = "(l.name LIKE ? OR l.about LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }

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

$countSQL = "SELECT COUNT(DISTINCT l.id)

             FROM lawyers l

             LEFT JOIN states s
                ON l.state_id = s.id

             LEFT JOIN cities c
                ON l.city_id = c.id

             LEFT JOIN lawyer_expertise le
                ON l.id = le.lawyer_id

             LEFT JOIN legal_categories lc
                ON le.category_id = lc.id

             WHERE $whereSQL";
$countStmt = $db->prepare($countSQL);
$countStmt->execute($params);
$total     = (int)$countStmt->fetchColumn();
$totalPages = max(1, ceil($total / $perPage));
$offset    = ($page - 1) * $perPage;

$sql = "SELECT DISTINCT l.*, s.name AS state_name, c.name AS city_name,
        GROUP_CONCAT(DISTINCT lc.name SEPARATOR ', ') AS practice_areas
        FROM lawyers l
        LEFT JOIN states s ON l.state_id=s.id
        LEFT JOIN cities c ON l.city_id=c.id
        LEFT JOIN lawyer_expertise le ON l.id=le.lawyer_id
        LEFT JOIN legal_categories lc ON le.category_id=lc.id
        WHERE $whereSQL
        GROUP BY l.id
        ORDER BY l.is_featured DESC, l.rating DESC, l.id DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$lawyers = $stmt->fetchAll();

// Active category label
$activeCat = null;

if ($categoryId > 0) {

    foreach ($categories as $c) {

        if ($c['id'] == $categoryId) {

            $activeCat = $c;
            break;
        }
    }
}
$pageTitle = ($activeCat ? $activeCat['name'].' Lawyers' : 'Find Lawyers') . ' — MeeVakeel';
require_once __DIR__ . '/includes/header.php';
?>

<!-- Page Hero -->
<section class="page-hero">
  <div class="container">
    <nav aria-label="breadcrumb"><ol class="breadcrumb mb-3">
      <li class="breadcrumb-item"><a href="/">Home</a></li>
      <li class="breadcrumb-item active"><?= $activeCat ? htmlspecialchars($activeCat['name']) : 'Find Lawyers' ?></li>
    </ol></nav>
    <h1 class="mb-1"><?= $activeCat ? 'Expert <span style="color:var(--gold);">'.htmlspecialchars($activeCat['name']).'</span> Lawyers' : 'Find <span style="color:var(--gold);">Verified Lawyers</span>' ?></h1>
    <p style="color:rgba(255,255,255,.72);">Browse <?= $total ?> verified lawyer<?= $total!==1?'s':'' ?> across India</p>
  </div>
</section>

<section style="background:var(--off-white);padding:48px 0;">
<div class="container">

  <!-- ── Filter Bar ── -->
  <div style="background:white;border-radius:16px;padding:24px;box-shadow:var(--shadow);border:1px solid var(--border);margin-bottom:32px;">
    <form method="GET" action="<?= SITE_URL ?>/lawyers.php">
      <div class="row g-3 align-items-end">
        <div class="col-md-3">
          <label class="filter-label">Practice Area</label>
          <select name="category" class="form-select">
            <option value="">All Categories</option>
            <?php foreach ($categories as $c): ?>
            <option value="<?= $c['id'] ?>" <?= $categoryId == $c['id'] ? 'selected' : '' ?>>
    <?= htmlspecialchars($c['name']) ?>
</option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="filter-label">State</label>
          <select name="state" class="form-select" id="filter_state">
            <option value="">All States</option>
            <?php foreach ($states as $s): ?>
            <option value="<?= $s['id'] ?>" <?= $stateId==$s['id']?'selected':'' ?>><?= $s['name'] ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="filter-label">City</label>
          <select name="city" id="filter_city" class="form-select">
            <option value="">All Cities</option>
            <?php
            if ($stateId) {
                $fc = $db->prepare("SELECT * FROM cities WHERE state_id=? ORDER BY name");
                $fc->execute([$stateId]);
                foreach ($fc->fetchAll() as $ci): ?>
                <option value="<?= $ci['id'] ?>" <?= $cityId==$ci['id']?'selected':'' ?>><?= $ci['name'] ?></option>
                <?php endforeach;
            }
            ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="filter-label">Experience</label>
          <select name="experience" class="form-select">
            <option value="">Any</option>
            <option value="2-4"  <?= $exp==='2-4'?'selected':'' ?>>2–4 Years</option>
            <option value="5-10" <?= $exp==='5-10'?'selected':'' ?>>5–10 Years</option>
            <option value="10+"  <?= $exp==='10+'?'selected':'' ?>>10+ Years</option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="filter-label">Search Name</label>
          <input type="text" name="q" class="form-control" placeholder="Lawyer name..." value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-1">
          <button type="submit" class="btn btn-gold w-100 py-2"><i class="fas fa-search"></i></button>
        </div>
      </div>
    </form>
  </div>

  <!-- Results info -->
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:10px;">
    <span style="font-size:.88rem;color:var(--text-light);">
      Showing <strong><?= count($lawyers) ?></strong> of <strong><?= $total ?></strong> lawyers
      <?= $categoryId ? ' in <strong>'.htmlspecialchars($activeCat['name']).'</strong>' : '' ?>
    </span>
<?php if ($search || $categoryId || $stateId || $exp): ?>
    <a href="lawyers.php" style="font-size:.82rem;color:var(--primary);font-weight:600;">
      <i class="fas fa-times me-1"></i>Clear filters
    </a>
    <?php endif; ?>
  </div>

  <?php if (empty($lawyers)): ?>
  <div style="text-align:center;padding:80px 0;">
    <i class="fas fa-user-slash" style="font-size:3rem;color:var(--border);margin-bottom:16px;display:block;"></i>
    <h5 style="color:var(--primary);">No lawyers found</h5>
    <p style="color:var(--text-light);font-size:.9rem;">Try adjusting your filters.</p>
    <a href="<?= SITE_URL ?>/lawyers.php"
   class="btn btn-primary-dark mt-2">

    View All Lawyers

</a>
  </div>
  <?php else: ?>

  <!-- ── Lawyer Cards ── -->
  <div class="row g-4">
   <?php foreach ($lawyers as $l):
$photoUrl = $l['profile_photo']
    ? '/nyaya-guru/assets/uploads/profiles/' . $l['profile_photo']
    : null;
    $nameParts = explode(' ', trim($l['name']));

    $initials =
        strtoupper(substr($nameParts[0], 0, 1)) .
        (isset($nameParts[1]) ? strtoupper(substr($nameParts[1], 0, 1)) : '');

    $freeConsult = ($l['experience_years'] === '2-4');

?>
    <div class="col-lg-4 col-md-6">
      <div class="lawyer-card">
        <div class="lawyer-card-header">
          <?php if ($l['is_featured']): ?><span class="featured-badge">⭐ Featured</span><?php endif; ?>
          <span class="verified-badge"><i class="fas fa-check-circle"></i> Verified</span>
          <?php if ($photoUrl): ?>
            <img src="<?= $photoUrl ?>" alt="<?= htmlspecialchars($l['name']) ?>" class="lawyer-avatar" onerror="this.style.display='none';this.nextSibling.style.display='flex';">
            <div class="lawyer-avatar-placeholder" style="display:none;"><?= $initials ?></div>
          <?php else: ?>
            <div class="lawyer-avatar-placeholder"><?= $initials ?></div>
          <?php endif; ?>
          <div class="lawyer-name"><?= htmlspecialchars($l['name']) ?></div>
          <span class="lawyer-exp-badge"><?= getExperienceLabel($l['experience_years']) ?> Experience</span>
        </div>
        <div class="lawyer-card-body">
          <?php if ($l['practice_areas']): ?>
          <div class="lawyer-practice"><?= htmlspecialchars(mb_strimwidth($l['practice_areas'],0,45,'...')) ?></div>
          <?php endif; ?>
          <div class="lawyer-info-row">
            <span class="lawyer-info-item">
              <i class="fas fa-map-marker-alt"></i>
              <?= htmlspecialchars($l['city_name'] ?? ($l['state_name'] ?? 'India')) ?>
            </span>
            <?php if ($l['languages']): ?>
            <span class="lawyer-info-item">
              <i class="fas fa-language"></i>
              <?= htmlspecialchars(ucfirst(explode(',',$l['languages'])[0])) ?>
            </span>
            <?php endif; ?>
          </div>
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <?= getLawyerRatingStars($l['rating']) ?>
              <span class="rating-text"><?= number_format($l['rating'],1) ?> (<?= $l['total_reviews'] ?> reviews)</span>
            </div>
            <div class="lawyer-fee">
              <?php if ($freeConsult): ?>
                <span style="color:var(--success);font-size:1rem;">Free*</span>
              <?php else: ?>
                ₹<?= number_format($l['consultation_fee'],0) ?>
              <?php endif; ?>
              <small>/session</small>
            </div>
          </div>
        </div>
        <div class="lawyer-card-footer">
          <a href="lawyer-details.php?id=<?= $l['id'] ?>" class="btn-book">
            <i class="fas fa-calendar-check me-1"></i>Book Consultation
          </a>
          <a href="<?= SITE_URL ?>/lawyer-details.php?id=<?= $l['id'] ?>"
   class="btn-profile">

    <i class="fas fa-eye"></i>

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

  <!-- Pagination -->
  <?php if ($totalPages > 1): ?>
  <nav style="margin-top:40px;">
    <ul class="pagination justify-content-center gap-1">
      <?php if ($page > 1): ?>
      <li class="page-item">
        <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>"
           style="border-radius:10px;border:1px solid var(--border);color:var(--primary);padding:10px 16px;">
          <i class="fas fa-chevron-left"></i>
        </a>
      </li>
      <?php endif; ?>
      <?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:10px 16px;">
          <?= $p ?>
        </a>
      </li>
      <?php endfor; ?>
      <?php if ($page < $totalPages): ?>
      <li class="page-item">
        <a class="page-link" href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>"
           style="border-radius:10px;border:1px solid var(--border);color:var(--primary);padding:10px 16px;">
          <i class="fas fa-chevron-right"></i>
        </a>
      </li>
      <?php endif; ?>
    </ul>
  </nav>
  <?php endif; ?>
  <?php endif; ?>

</div>
</section>

<script>
document.getElementById('filter_state').addEventListener('change', function() {
  var sid = this.value, sel = document.getElementById('filter_city');
  sel.innerHTML = '<option value="">Loading...</option>';
  if (!sid) { sel.innerHTML = '<option value="">All Cities</option>'; return; }
  fetch('/nyaya-guru/api/get_cities.php?state_id='+sid)
    .then(r=>r.json()).then(res=>{
      sel.innerHTML='<option value="">All Cities</option>';
      if(res.success) res.data.forEach(c=>sel.innerHTML+='<option value="'+c.id+'">'+c.name+'</option>');
    });
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>