<?php
require_once __DIR__.'/includes/functions.php';
$pageTitle = 'MJ Marketplace - Listings, Companies, Quotes and Chat';
$metaDescription = 'Discover trusted local companies, products, services, deals and listings by country, city and category on MJ Marketplace.';
$enableAutoCountryRedirect = true;
$area = visitor_area();
$areaLabel = visitor_area_label();
$priorityCountry = (int)($area['country_id'] ?? 0);

if (!function_exists('str_contains')) { function str_contains($haystack, $needle): bool { return $needle === '' || strpos((string)$haystack, (string)$needle) !== false; } }
function mj_home_count_query(string $sql, array $params = []): int {
    try { $r = one($sql, $params); return (int)($r['c'] ?? 0); } catch (Throwable $e) { return 0; }
}
function mj_home_rows_query(string $sql, array $params = []): array {
    try { return all_rows($sql, $params); } catch (Throwable $e) { return []; }
}
function mj_home_category_desc(string $name, string $type=''): string {
    $n = strtolower($name);
    if (str_contains($n,'data')) return 'Hard disk, SSD, RAID, NAS and urgent recovery services.';
    if (str_contains($n,'mobile') || str_contains($n,'phone')) return 'Phones, repairs, accessories and mobile services near you.';
    if (str_contains($n,'computer') || str_contains($n,'laptop') || str_contains($n,'it')) return 'IT support, laptops, networking, repair and business technology.';
    if (str_contains($n,'home')) return 'Home services, furniture, repairs, cleaning and household offers.';
    if (str_contains($n,'auto') || str_contains($n,'car')) return 'Cars, vehicle services, parts, rentals and automotive listings.';
    if (str_contains($n,'fashion')) return 'Clothing, accessories, lifestyle products and local sellers.';
    if (str_contains($n,'medical') || str_contains($n,'beauty')) return 'Clinics, beauty, wellness, aesthetic and care services.';
    if (str_contains($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.';
}
function mj_home_icon(string $name, string $fallback): string {
    $n = strtolower($name);
    if (str_contains($n,'data')) return 'bi-hdd-stack';
    if (str_contains($n,'mobile') || str_contains($n,'phone')) return 'bi-phone';
    if (str_contains($n,'computer') || str_contains($n,'laptop') || str_contains($n,'it')) return 'bi-laptop';
    if (str_contains($n,'home')) return 'bi-house-heart';
    if (str_contains($n,'auto') || str_contains($n,'car')) return 'bi-car-front';
    if (str_contains($n,'fashion')) return 'bi-bag-heart';
    if (str_contains($n,'medical') || str_contains($n,'beauty')) return 'bi-heart-pulse';
    if (str_contains($n,'education')) return 'bi-mortarboard';
    if (str_contains($n,'food')) return 'bi-cup-hot';
    return $fallback;
}

$countries = safe_all_rows_public('SELECT * FROM mj_countries WHERE is_active=1 ORDER BY CASE WHEN id=' . $priorityCountry . ' THEN 0 ELSE 1 END, FIELD(iso2,"SG","IN","MY","TH","ID","PH","AE","GB","US","AU") DESC, name LIMIT 10');
$cats = safe_all_rows_public('SELECT * FROM mj_categories WHERE is_active=1 ORDER BY sort_order,name LIMIT 12');
$listings = mj_public_fetch_listings(['area'=>$area ?? visitor_area(), 'soft_area'=>1], 12);
$companies = mj_public_fetch_companies(['area'=>$area ?? visitor_area(), 'soft_area'=>1], 8);

$totalListings = mj_home_count_query('SELECT COUNT(*) c FROM mj_listings WHERE status IN ("active","approved","published")');
$totalCompanies = mj_home_count_query('SELECT COUNT(*) c FROM mj_companies WHERE status IN ("active","approved","published")');
$totalCountries = mj_home_count_query('SELECT COUNT(*) c FROM mj_countries WHERE is_active=1');
$totalChats = table_exists('mj_chats') ? mj_home_count_query('SELECT COUNT(*) c FROM mj_chats') : 0;
$totalQuotes = table_exists('mj_quote_requests') ? mj_home_count_query('SELECT COUNT(*) c FROM mj_quote_requests') : 0;

$catListingCounts = [];
foreach (mj_home_rows_query('SELECT category_id, COUNT(*) c FROM mj_listings WHERE status IN ("active","approved","published") GROUP BY category_id') as $row) { $catListingCounts[(int)$row['category_id']] = (int)$row['c']; }
$catCompanyCounts = [];
foreach (mj_home_rows_query('SELECT category_id, COUNT(*) c FROM mj_companies WHERE status IN ("active","approved","published") GROUP BY category_id') as $row) { $catCompanyCounts[(int)$row['category_id']] = (int)$row['c']; }
$countryListingCounts = [];
foreach (mj_home_rows_query('SELECT country_id, COUNT(*) c FROM mj_listings WHERE status IN ("active","approved","published") GROUP BY country_id') as $row) { $countryListingCounts[(int)$row['country_id']] = (int)$row['c']; }
$countryCompanyCounts = [];
foreach (mj_home_rows_query('SELECT country_id, COUNT(*) c FROM mj_companies WHERE status IN ("active","approved","published") GROUP BY country_id') as $row) { $countryCompanyCounts[(int)$row['country_id']] = (int)$row['c']; }

include __DIR__.'/includes/header.php';
?>
<?php if (empty($countries) && empty($cats) && empty($listings) && empty($companies)): ?>
<div class="container mt-4"><div class="alert alert-warning rounded-4"><b>Homepage setup notice:</b> <?= e(mj_public_safe_query_notice()) ?> If this is a fresh install, open Admin and import sample data.</div></div>
<?php endif; ?>

<section class="mj-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">
          <?php if($areaLabel): ?><span class="mj-home-pill is-local"><i class="bi bi-geo-alt-fill me-1"></i>Showing nearby: <?=e($areaLabel)?></span><?php endif; ?>
          <span class="mj-home-pill"><i class="bi bi-shield-check me-1"></i>Verified companies</span>
          <span class="mj-home-pill"><i class="bi bi-chat-dots me-1"></i>Chat before dealing</span>
        </div>
        <h1>Find trusted companies, listings and local deals near you.</h1>
        <p class="mj-home-lead">Search products, services, business profiles and quote requests by country, city and category. Compare, chat, request quotation and contact sellers safely.</p>

        <form class="mj-home-search" method="get" action="<?= base_url('browse.php') ?>">
          <div class="row g-2 align-items-center">
            <div class="col-lg-5"><div class="mj-home-input"><i class="bi bi-search"></i><input class="form-control" name="q" placeholder="Search data recovery, phones, cars, services..."></div></div>
            <div class="col-lg-3"><select class="form-select" name="country_id"><option value="">All countries</option><?php foreach($countries as $c): ?><option value="<?=e($c['id'])?>"><?=e($c['flag_emoji'].' '.$c['name'])?></option><?php endforeach; ?></select></div>
            <div class="col-lg-2"><select class="form-select" name="type"><option value="">All</option><option value="product">Products</option><option value="service">Services</option><option value="rental">Rental</option><option value="vehicle">Vehicles</option></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>Popular:</span>
            <a href="<?=e(base_url('browse.php?q=data+recovery'))?>">Data recovery</a>
            <a href="<?=e(base_url('companies.php'))?>">Verified companies</a>
            <a href="<?=e(base_url('open-now.php'))?>">Open now</a>
            <a href="<?=e(base_url('services.php'))?>">Services</a>
          </div>
        </form>

        <div class="mj-home-stats mt-4">
          <div><b><?=e(number_format($totalListings))?></b><span>Active listings</span></div>
          <div><b><?=e(number_format($totalCompanies))?></b><span>Companies</span></div>
          <div><b><?=e(number_format($totalCountries))?></b><span>Countries</span></div>
          <div><b><?=e(number_format($totalChats + $totalQuotes))?></b><span>Chats & quotes</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>MJ Marketplace</b></div>
            <img src="<?= asset('images/marketplace-hero.svg') ?>" alt="Marketplace dashboard illustration">
            <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 company replies</small></div>
          <div class="mj-home-floating-card card-b"><i class="bi bi-chat-dots"></i><b>Live Chat</b><small>Ask before buying</small></div>
          <div class="mj-home-floating-card card-c"><i class="bi bi-patch-check-fill"></i><b>Trusted Seller</b><small>Verified profile</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>Explore</span><h2>Popular marketplace options</h2><p class="text-muted mb-0">Choose a category to browse listings, services, companies and local offers.</p></div><a href="<?=base_url('browse.php')?>" class="btn btn-outline-primary rounded-pill">Browse all listings</a></div>
    <div class="row g-3">
      <?php $fallbackIcons=['bi-phone','bi-laptop','bi-hdd-network','bi-car-front','bi-house','bi-tools','bi-cup-hot','bi-briefcase','bi-mortarboard','bi-calendar-event','bi-heart-pulse','bi-shop']; foreach($cats as $i=>$cat): $catId=(int)$cat['id']; $lc=$catListingCounts[$catId] ?? 0; $cc=$catCompanyCounts[$catId] ?? 0; $icon=mj_home_icon((string)$cat['name'], (string)($cat['icon'] ?: $fallbackIcons[$i%count($fallbackIcons)])); ?>
        <div class="col-md-6 col-xl-4">
          <a class="mj-home-category-card" href="<?=base_url('browse.php?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_home_category_desc((string)$cat['name'], (string)$cat['type']))?></small>
              <em><?=e($lc)?> listings • <?=e($cc)?> companies</em>
            </span>
            <i class="bi bi-arrow-right-circle"></i>
          </a>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<section class="mj-section bg-white mj-home-country-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>Local</span><h2>Browse by country</h2><p class="text-muted mb-0">Select a country to view local companies, listings, currency, timezone and deals.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('countries.php')?>">View all countries</a></div>
    <div class="row g-3">
      <?php foreach($countries as $c): $cid=(int)$c['id']; $lc=$countryListingCounts[$cid] ?? 0; $cc=$countryCompanyCounts[$cid] ?? 0; ?>
        <div class="col-md-6 col-xl-4">
          <a class="mj-home-country-card" href="<?=country_path($c)?>">
            <span class="flag"><?=e($c['flag_emoji'])?></span>
            <span class="flex-grow-1"><b><?=e($c['name'])?></b><small><?=e($c['currency_code'])?> • <?=e($c['timezone_default'])?></small><em><?=e($lc)?> listings • <?=e($cc)?> companies</em></span>
            <?php if($priorityCountry && $priorityCountry===$cid): ?><strong>Near you</strong><?php else: ?><i class="bi bi-arrow-up-right-circle"></i><?php endif; ?>
          </a>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<section class="mj-section mj-home-fresh-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>Fresh listings</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')?>">Browse more</a></div>
    <?php if(!$listings): ?><div class="alert alert-info rounded-4">No active listings yet. Import sample data or post your first listing.</div><?php else: ?>
      <div class="swiper mj-swiper mj-home-listing-swiper"><div class="swiper-wrapper"><?php foreach($listings as $r): ?><div class="swiper-slide"><?php include __DIR__.'/partials/listing-card.php'; ?></div><?php endforeach; ?></div><div class="swiper-pagination"></div></div>
    <?php endif; ?>
  </div>
</section>

<section class="mj-section bg-white mj-home-steps-section">
  <div class="container">
    <div class="row g-4 align-items-stretch">
      <div class="col-lg-4"><div class="mj-home-step-card main"><span class="mj-badge good mb-2"><i class="bi bi-shield-check"></i>Safer marketplace</span><h2>Contact, chat and request quotation with more confidence.</h2><p>MJ Marketplace gives buyers clear listing details, company profiles, saved items, chat, quotes and safety reminders before contacting a seller.</p><a class="btn btn-primary rounded-pill" href="<?=e(base_url('safety.php'))?>">Read safety tips</a></div></div>
      <?php $steps=[['bi-search-heart','Search & compare','Find listings, services and companies by country, city, category, price and open-now status.'],['bi-chat-dots','Chat safely','Ask questions, check availability and keep your conversation history in one place.'],['bi-receipt-cutoff','Request quotation','Send requirements to a company and track replies, status and accepted quotes.'],['bi-building-check','Trust company profiles','View services, branches, opening hours, profile score, trust score and verified badges.']]; foreach($steps as $s): ?>
        <div class="col-md-6 col-lg-2"><div class="mj-home-step-card"><div class="mj-icon-box mb-3"><i class="bi <?=e($s[0])?>"></i></div><h5><?=e($s[1])?></h5><p><?=e($s[2])?></p></div></div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<section class="mj-section mj-home-companies-section">
  <div class="container">
    <div class="row align-items-center g-5 mb-5">
      <div class="col-lg-5" data-aos="fade-right"><div class="mj-home-company-art"><img src="<?=asset('images/company-hero.svg')?>" alt="Company directory" class="img-fluid"><span><i class="bi bi-patch-check-fill"></i> Company verified</span></div></div>
      <div class="col-lg-7" data-aos="fade-left">
        <span class="mj-badge good mb-2"><i class="bi bi-building-check"></i>Company directory</span>
        <h2 class="fw-bold display-6">Discover businesses, services and trusted company profiles.</h2>
        <p class="text-muted">Companies can display their services, active listings, branches, opening hours, quote requests and trust signals so buyers understand who they are contacting.</p>
        <div class="row g-3 mt-2">
          <div class="col-md-4"><div class="mj-feature-card"><div class="mj-icon-box mb-3"><i class="bi bi-briefcase"></i></div><h5>Services</h5><p class="text-muted mb-0">Service catalog with starting price and quote request flow.</p></div></div>
          <div class="col-md-4"><div class="mj-feature-card"><div class="mj-icon-box mb-3"><i class="bi bi-geo-alt"></i></div><h5>Branches</h5><p class="text-muted mb-0">Local branch information, map and opening hours.</p></div></div>
          <div class="col-md-4"><div class="mj-feature-card"><div class="mj-icon-box mb-3"><i class="bi bi-star"></i></div><h5>Trust</h5><p class="text-muted mb-0">Verified badges, profile score, trust score and activity.</p></div></div>
        </div>
      </div>
    </div>
    <div class="mj-section-title mj-home-title"><h2>Featured companies</h2><a class="btn btn-outline-primary rounded-pill" href="<?=base_url('companies.php')?>">View companies</a></div>
    <?php if(!$companies): ?><div class="alert alert-info rounded-4">No active companies yet. Import sample data or add a 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>Start now</span><h2>Ready to sell, promote or request a quote?</h2><p>Post a listing, add a company profile or browse verified businesses near you.</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'))?>"><i class="bi bi-search me-1"></i>Find Companies</a></div>
    </div>
  </div>
</section>

<?php include __DIR__.'/includes/footer.php'; ?>
