<?php

require "core.php";

// Check if we have category parameter (new nested URL structure)
$categorySlug = isset($_GET['category']) ? clearGetData($_GET['category']) : null;
$slugItem = clearGetData(getSlugItem());

if(empty($slugItem) && !isset($slugItem)){
	header('Location: '. $urlPath->home());
}

// Get subcategory by slug
$itemDetails = getSubcategoryBySlug($connect, $slugItem);

if(empty($itemDetails)){
	header('Location: '. $urlPath->home());
}

// Get parent category details for nested URL
$parentCategory = null;
if ($itemDetails['subcategory_parent']) {
    $stmt = $connect->prepare("SELECT category_id, category_slug, category_title FROM categories WHERE category_id = ?");
    $stmt->execute([$itemDetails['subcategory_parent']]);
    $parentCategory = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Set ad display flags
$itemDetails['page_ad_header'] = 1;
$itemDetails['page_ad_footer'] = 1;
$itemDetails['page_footer'] = 1;

// Get sidebar data
$getCategories = getCategories($connect, 5);
$getStores = getStores($connect, 5);
$sidebarCampaigns = getSidebarCampaigns($connect, 2);

// Get coupons for this subcategory
$getResults = getCouponsBySubCategory($connect, $site_config['page_limit'], $itemDetails['subcategory_id']);

$items = $getResults['items'];
$total = $getResults['total'];

$numPages = numTotalPages($total, $site_config['page_limit']);

// SEO Title
$titleSeoHeader = !empty($itemDetails['subcategory_seotitle']) 
    ? $itemDetails['subcategory_seotitle'] 
    : $itemDetails['subcategory_title'] . ' Coupons, Deals & Cashback Offers | Alonedeals';

// SEO Description
$descriptionSeoHeader = !empty($itemDetails['subcategory_seodescription']) 
    ? $itemDetails['subcategory_seodescription'] 
    : 'Get the latest ' . $itemDetails['subcategory_title'] . ' coupons, promo codes & exclusive cashback offers on Alonedeals. Save more on every purchase today!';

// Canonical URL - use nested structure if parent category exists
if ($parentCategory && !empty($parentCategory['category_slug'])) {
    $canonicalUrl = SITE_URL . '/category/' . $parentCategory['category_slug'] . '/' . $itemDetails['subcategory_slug'];
} else {
    $canonicalUrl = SITE_URL . '/subcategory/' . $itemDetails['subcategory_slug'];
}

// Page Title
$pageTitle = $itemDetails['subcategory_title'];

include './header.php';
include './sections/header.php';
include './sections/views/header-ad.view.php';

require './views/single-subcategory.view.php';

include './sections/views/footer-ad.view.php';
include './sections/footer.php';
include './footer.php';

?>
