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

$slug = trim((string)($_GET['country'] ?? ''));
$country = country_by_slug($slug);

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 or not active.</div><a class="btn btn-primary" href="'.e(base_url('countries.php')).'">View Countries</a></div></section>';
    include __DIR__.'/includes/footer.php';
    exit;
}

$pageTitle = $country['name'].' Marketplace';
$metaDescription = $country['seo_description'] ?: 'Buy, sell, find companies, services and deals in '.$country['name'].'.';
$area = visitor_area();
$countryId = (int)$country['id'];
$countryThemeStyle = mj_v288_country_theme_style($country);
$countryThemeClass = mj_v288_country_theme($country)['class'] ?? '';

if (!function_exists('mj_country_has_text')) {
    function mj_country_has_text(string $haystack, string $needle): bool {
        return $needle === '' || stripos($haystack, $needle) !== false;
    }
}
if (!function_exists('mj_country_category_desc')) {
    function mj_country_category_desc(string $name, string $type=''): string {
        $n = strtolower($name);
        if (mj_country_has_text($n,'data')) return 'Hard disk, SSD, RAID, NAS and urgent recovery services.';
        if (mj_country_has_text($n,'mobile') || mj_country_has_text($n,'phone')) return 'Phones, repairs, accessories and mobile services near you.';
        if (mj_country_has_text($n,'computer') || mj_country_has_text($n,'laptop') || mj_country_has_text($n,'it')) return 'IT support, laptops, networking, repair and business technology.';
        if (mj_country_has_text($n,'home')) return 'Home services, furniture, repairs, cleaning and household offers.';
        if (mj_country_has_text($n,'auto') || mj_country_has_text($n,'car')) return 'Cars, vehicle services, parts, rentals and automotive listings.';
        if (mj_country_has_text($n,'fashion')) return 'Clothing, accessories, lifestyle products and local sellers.';
        if (mj_country_has_text($n,'medical') || mj_country_has_text($n,'beauty')) return 'Clinics, beauty, wellness, aesthetic and care services.';
        if (mj_country_has_text($n,'education')) return 'Courses, training, tutors and education providers.';
        if ($type === 'company') return 'Browse trusted companies, services and business profiles.';
        return 'Explore listings, companies, deals and local services.';
    }
}
if (!function_exists('mj_country_icon')) {
    function mj_country_icon(string $name, string $fallback='bi-grid'): string {
        $n = strtolower($name);
        if (mj_country_has_text($n,'data')) return 'bi-hdd-stack';
        if (mj_country_has_text($n,'mobile') || mj_country_has_text($n,'phone')) return 'bi-phone';
        if (mj_country_has_text($n,'computer') || mj_country_has_text($n,'laptop') || mj_country_has_text($n,'it')) return 'bi-laptop';
        if (mj_country_has_text($n,'home')) return 'bi-house-heart';
        if (mj_country_has_text($n,'auto') || mj_country_has_text($n,'car')) return 'bi-car-front';
        if (mj_country_has_text($n,'fashion')) return 'bi-bag-heart';
        if (mj_country_has_text($n,'medical') || mj_country_has_text($n,'beauty')) return 'bi-heart-pulse';
        if (mj_country_has_text($n,'education')) return 'bi-mortarboard';
        if (mj_country_has_text($n,'food')) return 'bi-cup-hot';
        return $fallback ?: 'bi-grid';
    }
}

$listings = mj_public_fetch_listings(['country_id'=>$countryId, 'area'=>$area, 'soft_area'=>1], 12);
$companies = mj_public_fetch_companies(['country_id'=>$countryId, 'area'=>$area, 'soft_area'=>1], 8);
$cats = safe_all_rows_public('SELECT * FROM mj_categories WHERE is_active=1 AND type IN ("marketplace","service","vehicle","property","job","course","event") ORDER BY sort_order,name LIMIT 12');
$states = safe_all_rows_public('SELECT * FROM mj_states WHERE country_id=? AND is_active=1 ORDER BY name LIMIT 12',[$countryId]);

$stats = [
  'listings' => safe_count_public('SELECT COUNT(*) c FROM mj_listings WHERE country_id=? AND '.mj_public_listing_status_sql('mj_listings'),[$countryId]),
  'companies' => safe_count_public('SELECT COUNT(*) c FROM mj_companies WHERE country_id=? AND '.mj_public_company_status_sql('mj_companies'),[$countryId]),
  'verified' => safe_count_public('SELECT COUNT(*) c FROM mj_companies WHERE country_id=? AND '.mj_public_company_status_sql('mj_companies').' AND is_verified=1',[$countryId]),
];

$catListingCounts = [];
foreach (safe_all_rows_public('SELECT category_id, COUNT(*) c FROM mj_listings WHERE country_id=? AND '.mj_public_listing_status_sql('mj_listings').' GROUP BY category_id',[$countryId]) as $row) {
    $catListingCounts[(int)$row['category_id']] = (int)$row['c'];
}
$catCompanyCounts = [];
foreach (safe_all_rows_public('SELECT category_id, COUNT(*) c FROM mj_companies WHERE country_id=? AND '.mj_public_company_status_sql('mj_companies').' GROUP BY category_id',[$countryId]) as $row) {
    $catCompanyCounts[(int)$row['category_id']] = (int)$row['c'];
}
$stateListingCounts = [];
foreach (safe_all_rows_public('SELECT state_id, COUNT(*) c FROM mj_listings WHERE country_id=? AND state_id IS NOT NULL AND '.mj_public_listing_status_sql('mj_listings').' GROUP BY state_id',[$countryId]) as $row) {
    $stateListingCounts[(int)$row['state_id']] = (int)$row['c'];
}
$stateCompanyCounts = [];
foreach (safe_all_rows_public('SELECT state_id, COUNT(*) c FROM mj_companies WHERE country_id=? AND state_id IS NOT NULL AND '.mj_public_company_status_sql('mj_companies').' GROUP BY state_id',[$countryId]) as $row) {
    $stateCompanyCounts[(int)$row['state_id']] = (int)$row['c'];
}

include __DIR__.'/includes/header.php';
?>
<div class="mj-country-theme-vars country-theme <?=e($countryThemeClass)?>" style="<?= $countryThemeStyle ?>"></div>
<section class="mj-home-hero mj-country-home-hero country-theme <?=e($countryThemeClass)?>" style="<?= $countryThemeStyle ?>">
  <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-currency-exchange me-1"></i><?=e($country['currency_code'] ?? 'USD')?></span>
          <span class="mj-home-pill"><i class="bi bi-clock-history me-1"></i><?=e($country['timezone_default'] ?? 'UTC')?></span>
        </div>
        <h1><?=e($country['name'])?> Marketplace</h1>
        <p class="mj-home-lead">Buy, sell, discover verified companies, request quotations and chat safely in <?=e($country['name'])?>. Browse by category, state, city, listing or company profile.</p>

        <form class="mj-home-search" action="<?=base_url('browse.php')?>" method="get">
          <input type="hidden" name="country_id" value="<?=e($countryId)?>">
          <div class="row g-2 align-items-center">
            <div class="col-lg-6"><div class="mj-home-input"><i class="bi bi-search"></i><input class="form-control" name="q" placeholder="Search in <?=e($country['name'])?>"></div></div>
            <div class="col-lg-4"><select class="form-select" name="category_id"><option value="">All categories</option><?php foreach($cats as $cat): ?><option value="<?=e($cat['id'])?>"><?=e($cat['name'])?></option><?php endforeach; ?></select></div>
            <div class="col-lg-2 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))?>">Listings</a>
            <a href="<?=e(base_url('companies.php?country_id='.$countryId))?>">Companies</a>
            <a href="<?=e(base_url('services.php?country_id='.$countryId))?>">Services</a>
            <a href="<?=e(base_url('open-now.php?country_id='.$countryId))?>">Open now</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['verified']))?></b><span>Verified</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($country['name'])?></b></div>
            <img src="<?=asset('images/marketplace-hero.svg')?>" alt="<?=e($country['name'])?> marketplace dashboard">
            <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-receipt-cutoff"></i><b>Request Quote</b><small>Compare local replies</small></div>
          <div class="mj-home-floating-card card-b"><i class="bi bi-chat-dots"></i><b>Chat Sellers</b><small>Ask before buying</small></div>
          <div class="mj-home-floating-card card-c"><i class="bi bi-patch-check-fill"></i><b>Verified</b><small><?=e($country['name'])?> companies</small></div>
        </div>
      </div>
    </div>
  </div>
</section>

<section class="mj-section 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-grid"></i>Categories</span><h2>Explore <?=e($country['name'])?></h2><p class="text-muted mb-0">Same homepage card design, filtered for <?=e($country['name'])?> marketplace listings and companies.</p></div>
      <a class="btn btn-outline-primary rounded-pill" href="<?=base_url('browse.php?country_id='.$countryId)?>">Browse all</a>
    </div>
    <?php if(!$cats): ?>
      <div class="alert alert-info rounded-4">No active categories found.</div>
    <?php else: ?>
      <div class="row g-3">
        <?php foreach($cats as $cat): $catId=(int)$cat['id']; $lc=$catListingCounts[$catId] ?? 0; $cc=$catCompanyCounts[$catId] ?? 0; $icon=mj_country_icon((string)$cat['name'], (string)($cat['icon'] ?: 'bi-grid')); ?>
          <div class="col-md-6 col-xl-3">
            <a class="mj-home-category-card" href="<?=base_url('browse.php?country_id='.$countryId.'&category_id='.$catId)?>">
              <span class="mj-home-cat-icon"><i class="bi <?=e($icon)?>"></i></span>
              <span class="flex-grow-1"><b><?=e($cat['name'])?></b><small><?=e(mj_country_category_desc((string)$cat['name'], (string)($cat['type'] ?? '')))?></small><em><?=e(number_format($lc))?> listings • <?=e(number_format($cc))?> companies</em></span>
              <i class="bi bi-arrow-right-circle"></i>
            </a>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</section>

<?php if($states): ?>
<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-map"></i>States / Regions</span><h2>Browse by location</h2><p class="text-muted mb-0">Select a state or region inside <?=e($country['name'])?>.</p></div>
    </div>
    <div class="row g-3">
      <?php foreach($states as $st): $sid=(int)$st['id']; ?>
        <div class="col-6 col-md-4 col-xl-3">
          <a class="mj-home-country-card h-100" href="<?=base_url($country['slug'].'/'.$st['slug'].'/')?>">
            <span class="flag"><i class="bi bi-pin-map"></i></span>
            <span class="flex-grow-1"><b><?=e($st['name'])?></b><small><?=e($st['timezone'] ?: $country['timezone_default'])?></small><em><?=e(number_format($stateListingCounts[$sid] ?? 0))?> listings • <?=e(number_format($stateCompanyCounts[$sid] ?? 0))?> companies</em></span>
            <i class="bi bi-chevron-right"></i>
          </a>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>

<section class="mj-section<?= $states ? '' : ' bg-white' ?>">
  <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>Latest in <?=e($country['name'])?></h2><p class="text-muted mb-0">Recently posted products, services and offers from active sellers.</p></div>
      <a class="btn btn-outline-primary rounded-pill" href="<?=base_url('browse.php?country_id='.$countryId)?>">View all</a>
    </div>
    <?php if(!$listings): ?>
      <div class="text-center py-5"><img src="<?=asset('images/empty-state.svg')?>" class="img-fluid" style="max-width:360px" alt="No listings"><h3 class="fw-bold mt-3">No listings in <?=e($country['name'])?> yet</h3><p class="text-muted">Post a listing or import sample data from admin.</p><a class="btn btn-primary rounded-pill" href="<?=base_url('post-listing.php')?>">Post first listing</a></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>Company directory</span><h2>Companies in <?=e($country['name'])?></h2><p class="text-muted mb-0">Trusted company profiles, services, branches, quotes and contact options.</p></div>
      <a class="btn btn-outline-primary rounded-pill" href="<?=base_url('companies.php?country_id='.$countryId)?>">View all companies</a>
    </div>
    <?php if(!$companies): ?>
      <div class="alert alert-info rounded-4">No active companies yet. Import Business Seed or let business owners add their company.</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>

<section class="mj-section mj-home-cta-section">
  <div class="container">
    <div class="mj-home-cta">
      <div><span class="mj-badge mb-2"><i class="bi bi-lightning-charge"></i><?=e($country['name'])?></span><h2>Ready to sell or request a quote?</h2><p>Post a listing, add a company profile or browse verified businesses in <?=e($country['name'])?>.</p></div>
      <div class="d-flex flex-wrap gap-2"><a class="btn btn-light rounded-pill" href="<?=e(base_url('post-listing.php'))?>"><i class="bi bi-plus-circle me-1"></i>Post Listing</a><a class="btn btn-outline-light rounded-pill" href="<?=e(base_url('add-company.php'))?>"><i class="bi bi-building-add me-1"></i>Add Company</a><a class="btn btn-outline-light rounded-pill" href="<?=e(base_url('companies.php?country_id='.$countryId))?>"><i class="bi bi-search me-1"></i>Find Companies</a></div>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
