<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

$states   = getStates($pdo);
$cats     = getCategories($pdo,'service');

$keyword  = trim($_GET['q'] ?? $_GET['keyword'] ?? '');
$catSlug  = trim($_GET['cat'] ?? '');
$stateId  = (int)($_GET['state_id'] ?? 0);
$distId   = (int)($_GET['district_id'] ?? 0);
$areaId   = (int)($_GET['area_id'] ?? 0);
$sort     = trim($_GET['sort'] ?? 'featured');
$verified = !empty($_GET['verified']);

$filters = [
    'keyword'     => $keyword,
    'category'    => $catSlug,
    'type'        => 'service',
    'state_id'    => $stateId ?: null,
    'district_id' => $distId  ?: null,
    'area_id'     => $areaId  ?: null,
    'sort'        => $sort,
    'verified'    => $verified,
];
$vendors = searchVendors($pdo, $filters);

// Pre-load districts/areas for selected values
$districts = $stateId  ? getDistricts($pdo,$stateId) : [];
$areas     = $distId   ? getAreas($pdo,$distId)      : [];

$pageTitle    = ($catSlug ? ucfirst(str_replace('-',' ',$catSlug)) . ' Services' : 'Find Services') . ' | EzyBookNow';
$pageDesc     = 'Find verified ' . ($catSlug ?: 'home service') . ' providers near you.';
require_once 'includes/header.php';
?>
<div class="container" style="padding-top:16px;padding-bottom:80px">
  <nav class="breadcrumb"><a href="<?=SITE_URL?>">Home</a> <span>›</span> <span>Services</span></nav>
  <h1 class="page-title"><?=$catSlug?ucfirst(str_replace('-',' ',$catSlug)).' Services':'Find Service Providers'?></h1>

  <!-- Search + Filter Form -->
  <div class="search-filter-card">
    <form method="GET" id="searchForm">
      <div class="filter-row">
        <div class="filter-item keyword-input">
          <input type="text" name="q" value="<?=e($keyword)?>" class="form-control" placeholder="🔍 Electrician, plumber, painter...">
        </div>
        <div class="filter-item">
          <select name="state_id" id="state_id" class="form-control form-select" onchange="loadDistricts(this.value)">
            <option value="">📍 All States</option>
            <?php foreach($states as $s): ?>
            <option value="<?=$s['id']?>" <?=$stateId==$s['id']?'selected':''?>><?=e($s['name'])?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-item">
          <select name="district_id" id="district_id" class="form-control form-select" onchange="loadAreas(this.value)">
            <option value="">🏙️ All Districts</option>
            <?php foreach($districts as $d): ?>
            <option value="<?=$d['id']?>" <?=$distId==$d['id']?'selected':''?>><?=e($d['name'])?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-item">
          <select name="area_id" id="area_id" class="form-control form-select">
            <option value="">🗺️ All Areas</option>
            <?php foreach($areas as $a): ?>
            <option value="<?=$a['id']?>" <?=$areaId==$a['id']?'selected':''?>><?=e($a['name'])?><?=$a['pincode']?' - '.$a['pincode']:''?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-item">
          <select name="cat" class="form-control form-select">
            <option value="">All Categories</option>
            <?php foreach($cats as $c): ?>
            <option value="<?=e($c['slug'])?>" <?=$catSlug===$c['slug']?'selected':''?>><?=e($c['icon'].' '.$c['name'])?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="filter-item">
          <select name="sort" class="form-control form-select">
            <option value="featured" <?=$sort==='featured'?'selected':''?>>⭐ Featured</option>
            <option value="rating"   <?=$sort==='rating'?'selected':''?>>🏆 Top Rated</option>
            <option value="newest"   <?=$sort==='newest'?'selected':''?>>🆕 Newest</option>
          </select>
        </div>
        <button type="submit" class="btn btn-primary filter-btn">Search</button>
      </div>
      <div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:10px;align-items:center">
        <label style="display:flex;align-items:center;gap:6px;font-size:.83rem;cursor:pointer;color:var(--text-muted)">
          <input type="checkbox" name="verified" value="1" <?=$verified?'checked':''?>> ✅ Verified Only
        </label>
        <?php foreach($cats as $c): ?>
        <a href="?cat=<?=e($c['slug'])?>" class="tag <?=$catSlug===$c['slug']?'tag-active':''?>"><?=e($c['icon'].' '.$c['name'])?></a>
        <?php endforeach; ?>
      </div>
    </form>
  </div>

  <!-- Results -->
  <div style="margin:16px 0;font-size:.875rem;color:var(--text-muted)">
    <?=count($vendors)?> service provider<?=count($vendors)!==1?'s':''?> found
    <?=$keyword?' for "<strong>'.e($keyword).'</strong>"':''?>
    <?=$catSlug?' in <strong>'.ucfirst(str_replace('-',' ',$catSlug)).'</strong>':''?>
  </div>

  <?php if(empty($vendors)): ?>
  <div class="empty-state" style="margin-top:40px">
    <div class="empty-state-icon">🔍</div>
    <h3>No service providers found</h3>
    <p>Try changing your search or location filters</p>
    <a href="<?=SITE_URL?>/services.php" class="btn btn-primary mt-2">Clear Filters</a>
  </div>
  <?php else: ?>
  <div class="vendor-grid">
    <?php foreach($vendors as $v): ?>
    <a href="<?=SITE_URL?>/vendor.php?slug=<?=e($v['slug'])?>" class="vendor-card-link">
      <div class="vendor-card">
        <div class="vendor-card-banner" style="background:linear-gradient(135deg,var(--primary-dark,#0f2f7a),var(--primary))">
          <?php if($v['banner']||$v['logo']): ?>
          <img src="<?=e($v['banner']?:$v['logo'])?>" alt="<?=e($v['business_name'])?>" loading="lazy">
          <?php else: ?><span style="font-size:2rem"><?=e($v['cat_icon']??'🔧')?></span><?php endif; ?>
        </div>
        <div class="vendor-card-body">
          <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px">
            <h3 class="vendor-name"><?=e($v['business_name'])?></h3>
            <?php if($v['is_verified']): ?><span class="verified-badge">✅ Verified</span><?php endif; ?>
          </div>
          <div class="vendor-cat"><?=e($v['cat_icon']??'')?> <?=e($v['cat_name']??'')?></div>
          <div class="vendor-loc">📍 <?=e($v['area_name']??$v['district_name']??$v['state_name']??'India')?></div>
          <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">
            <div style="display:flex;align-items:center;gap:4px">
              <?=renderStars((float)($v['rating']??0))?>
              <span style="font-size:.78rem;color:var(--text-muted)">(<?=$v['rating_count']??0?>)</span>
            </div>
            <span style="font-size:.78rem;color:var(--text-muted)">⏱ <?=e($v['response_time']??'1 Hour')?></span>
          </div>
        </div>
      </div>
    </a>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</div>
<script>
function loadDistricts(stateId) {
  var d=document.getElementById('district_id'), a=document.getElementById('area_id');
  d.innerHTML='<option value="">🏙️ All Districts</option>';
  a.innerHTML='<option value="">🗺️ All Areas</option>';
  if(!stateId) return;
  fetch('<?=SITE_URL?>/api/location.php?action=districts&state_id='+stateId)
    .then(function(r){return r.json();})
    .then(function(data){data.forEach(function(x){d.insertAdjacentHTML('beforeend','<option value="'+x.id+'">'+x.name+'</option>');});})
    .catch(function(e){console.error('Districts error',e);});
}
function loadAreas(distId) {
  var a=document.getElementById('area_id');
  a.innerHTML='<option value="">🗺️ All Areas</option>';
  if(!distId) return;
  fetch('<?=SITE_URL?>/api/location.php?action=areas&district_id='+distId)
    .then(function(r){return r.json();})
    .then(function(data){data.forEach(function(x){a.insertAdjacentHTML('beforeend','<option value="'+x.id+'">'+x.name+(x.pincode?' - '+x.pincode:'')+'</option>');});})
    .catch(function(e){console.error('Areas error',e);});
}
</script>
<?php require_once 'includes/footer.php'; ?>