<?php
// Use absolute paths to ensure files are found
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/functions.php';

// For debugging - uncomment to help diagnose issues
// file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/router_debug.log', date('Y-m-d H:i:s') . ": Slug: " . ($_GET['slug'] ?? 'NONE') . "\n", FILE_APPEND);

$slug = isset($_GET['slug']) ? $_GET['slug'] : '';

if (empty($slug)) {
    header('Location: /');
    exit;
}

// Check if it's a product
$product = get_product_by_slug($slug);
if ($product) {
    // file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/router_debug.log', date('Y-m-d H:i:s') . ": Found product: " . $slug . "\n", FILE_APPEND);
    $_GET['product'] = $slug;
    include $_SERVER['DOCUMENT_ROOT'] . '/product.php';
    exit;
}

// Check if it's a category - DIRECT MATCH WITH DB
$category = get_category_by_slug($slug);
if ($category) {
    // file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/router_debug.log', date('Y-m-d H:i:s') . ": Found category: " . $slug . "\n", FILE_APPEND);
    $_GET['category'] = $slug; // Use the actual slug, don't transform it
    include $_SERVER['DOCUMENT_ROOT'] . '/category.php';
    exit;
}

// If we get here, nothing matches - show 404
// file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/router_debug.log', date('Y-m-d H:i:s') . ": 404 for: " . $slug . "\n", FILE_APPEND);
http_response_code(404);
include $_SERVER['DOCUMENT_ROOT'] . '/404.php';
exit;