<?php
require_once __DIR__.'/includes/functions.php';
$country = country_by_slug($_GET['country'] ?? '');
if(!$country){ http_response_code(404); $pageTitle='Country not found'; include __DIR__.'/includes/header.php'; echo '<section class="mj-section"><div class="container"><div class="alert alert-warning rounded-4">Country not found.</div></div></section>'; include __DIR__.'/includes/footer.php'; exit; }
$state = state_by_slug((int)$country['id'], $_GET['state'] ?? '');
if(!$state){ http_response_code(404); $pageTitle='State not found'; include __DIR__.'/includes/header.php'; echo '<section class="mj-section"><div class="container"><div class="alert alert-warning rounded-4">State / region not found.</div></div></section>'; include __DIR__.'/includes/footer.php'; exit; }

$countryId = (int)$country['id'];
$stateId = (int)$state['id'];
$pageTitle = $state['name'].' '.$country['name'].' Marketplace';
$metaDescription = 'Browse listings and companies in '.$state['name'].', '.$country['name'].'.';
$timezone = $state['timezone'] ?: ($country['timezone_default'] ?? 'UTC');
$listings=mj_public_fetch_listings(['country_id'=>$countryId, 'state_id'=>$stateId], 12);
$companies=mj_public_fetch_companies(['country_id'=>$countryId, 'state_id'=>$stateId], 12);
$cities=safe_all_rows_public('SELECT * FROM mj_cities WHERE country_id=? AND state_id=? AND is_active=1 ORDER BY name LIMIT 24',[$countryId,$stateId]);
$stats = [
  'listings' => safe_count_public('SELECT COUNT(*) c FROM mj_listings WHERE country_id=? AND state_id=? AND '.mj_public_listing_status_sql('mj_listings'),[$countryId,$stateId]),
  'companies' => safe_count_public('SELECT COUNT(*) c FROM mj_companies WHERE country_id=? AND state_id=? AND '.mj_public_company_status_sql('mj_companies'),[$countryId,$stateId]),
  'cities' => count($cities),
];
$cityListingCounts = [];
foreach (safe_all_rows_public('SELECT city_id, COUNT(*) c FROM mj_listings WHERE country_id=? AND state_id=? AND city_id IS NOT NULL AND '.mj_public_listing_status_sql('mj_listings').' GROUP BY city_id',[$countryId,$stateId]) as $row) {
    $cityListingCounts[(int)$row['city_id']] = (int)$row['c'];
}
$cityCompanyCounts = [];
foreach (safe_all_rows_public('SELECT city_id, COUNT(*) c FROM mj_companies WHERE country_id=? AND state_id=? AND city_id IS NOT NULL AND '.mj_public_company_status_sql('mj_companies').' GROUP BY city_id',[$countryId,$stateId]) as $row) {
    $cityCompanyCounts[(int)$row['city_id']] = (int)$row['c'];
}
include __DIR__.'/includes/header.php';
?>
<section class="mj-home-hero mj-country-home-hero">
  <div class="container position-relative">
    <div class="row align-items-center g-5">
      <div class="col-lg-7" data-aos="fade-right">
        <div class="d-flex flex-wrap gap-2 mb-3">
          <span class="mj-home-pill is-local"><i class="bi bi-geo-alt-fill me-1"></i><?=e(($country['flag_emoji'] ?? '').' '.$country['name'])?></span>
          <span class="mj-home-pill"><i class="bi bi-map me-1"></i><?=e($state['name'])?></span>
          <span class="mj-home-pill"><i class="bi bi-clock-history me-1"></i><?=e($timezone)?></span>
        </div>
        <h1><?=e($state['name'])?> Marketplace</h1>
        <p class="mj-home-lead">Browse local cities, listings and verified companies in <?=e($state['name'])?>, <?=e($country['name'])?>.</p>
        <form class="mj-home-search" action="<?=base_url('browse.php')?>" method="get">
          <input type="hidden" name="country_id" value="<?=e($countryId)?>"><input type="hidden" name="state_id" value="<?=e($stateId)?>">
          <div class="row g-2 align-items-center">
            <div class="col-lg-8"><div class="mj-home-input"><i class="bi bi-search"></i><input class="form-control" name="q" placeholder="Search in <?=e($state['name'])?>"></div></div>
            <div class="col-lg-4 d-grid"><button class="btn btn-primary"><i class="bi bi-search me-1"></i>Search</button></div>
          </div>
          <div class="mj-home-quick mt-3"><span>Quick:</span><a href="<?=e(base_url('browse.php?country_id='.$countryId.'&state_id='.$stateId))?>">Listings</a><a href="<?=e(base_url('companies.php?country_id='.$countryId.'&state_id='.$stateId))?>">Companies</a><a href="<?=e(base_url($country['slug'].'/'))?>">Back to <?=e($country['name'])?></a></div>
        </form>
        <div class="mj-home-stats mj-country-stats mt-4"><div><b><?=e(number_format((int)$stats['listings']))?></b><span>Listings</span></div><div><b><?=e(number_format((int)$stats['companies']))?></b><span>Companies</span></div><div><b><?=e(number_format((int)$stats['cities']))?></b><span>Cities</span></div></div>
      </div>
      <div class="col-lg-5" data-aos="fade-left"><div class="mj-home-hero-board"><div class="mj-home-window"><div class="mj-window-top"><span></span><span></span><span></span><b><?=e($state['name'])?></b></div><img src="<?=asset('images/marketplace-hero.svg')?>" alt="<?=e($state['name'])?> marketplace"><div class="mj-home-check"><i class="bi bi-check-lg"></i></div></div><div class="mj-home-floating-card card-a"><i class="bi bi-geo"></i><b>Cities</b><small>Local browsing</small></div><div class="mj-home-floating-card card-b"><i class="bi bi-chat-dots"></i><b>Chat</b><small>Ask sellers</small></div><div class="mj-home-floating-card card-c"><i class="bi bi-building-check"></i><b>Companies</b><small>Verified profiles</small></div></div></div>
    </div>
  </div>
</section>

<?php if($cities): ?>
<section class="mj-section mj-home-category-section"><div class="container"><div class="mj-section-title mj-home-title"><div><span class="mj-badge good mb-2"><i class="bi bi-geo-alt"></i>Cities</span><h2>Cities in <?=e($state['name'])?></h2><p class="text-muted mb-0">Browse city marketplace pages with the same homepage card design.</p></div></div><div class="row g-3"><?php foreach($cities as $ci): $cityId=(int)$ci['id']; ?><div class="col-6 col-md-4 col-xl-3"><a class="mj-home-country-card h-100" href="<?=base_url($country['slug'].'/'.$state['slug'].'/'.$ci['slug'].'/')?>"><span class="flag"><i class="bi bi-geo-alt"></i></span><span class="flex-grow-1"><b><?=e($ci['name'])?></b><small><?=e($ci['timezone'] ?: $timezone)?></small><em><?=e(number_format($cityListingCounts[$cityId] ?? 0))?> listings • <?=e(number_format($cityCompanyCounts[$cityId] ?? 0))?> companies</em></span><i class="bi bi-chevron-right"></i></a></div><?php endforeach; ?></div></div></section>
<?php endif; ?>

<section class="mj-section<?= $cities ? ' bg-white' : ' mj-home-category-section' ?>"><div class="container"><div class="mj-section-title mj-home-title"><div><span class="mj-badge mb-2"><i class="bi bi-tags"></i>Latest</span><h2>Listings in <?=e($state['name'])?></h2><p class="text-muted mb-0">Newest active listings in this state / region.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('browse.php?country_id='.$countryId.'&state_id='.$stateId)?>">Browse all</a></div><?php if(!$listings): ?><div class="alert alert-info rounded-4">No active listings in this state yet.</div><?php else: ?><div class="row g-4"><?php foreach($listings as $r): ?><div class="col-md-6 col-xl-3"><?php include __DIR__.'/partials/listing-card.php'; ?></div><?php endforeach; ?></div><?php endif; ?></div></section>
<section class="mj-section bg-white"><div class="container"><div class="mj-section-title mj-home-title"><div><span class="mj-badge good mb-2"><i class="bi bi-building-check"></i>Companies</span><h2>Companies in <?=e($state['name'])?></h2><p class="text-muted mb-0">Trusted company profiles in this state / region.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('companies.php?country_id='.$countryId.'&state_id='.$stateId)?>">View companies</a></div><?php if(!$companies): ?><div class="alert alert-info rounded-4">No active companies in this state yet.</div><?php else: ?><div class="row g-4"><?php foreach($companies as $r): ?><div class="col-md-6 col-xl-3"><?php include __DIR__.'/partials/company-card.php'; ?></div><?php endforeach; ?></div><?php endif; ?></div></section>
<?php include __DIR__.'/includes/footer.php'; ?>
