<?php
declare(strict_types=1);

$base_url = 'https://topdigitalmarketingcompanies.in';

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: geolocation=(), microphone=(), camera=(), payment=(), usb=()');

require_once 'data/all-category.php';
require_once 'data/all-therapeutic.php';
require_once 'data/blogs-data.php';
require_once 'data/page-data.php';

$blog_limit = 3;
$product_limit = 12;

/*$page_action = isset($_GET['page']) ? clean_slug($_GET['page']) : 'home';
$p = isset($_GET['p']) ? max(1, (int) $_GET['p']) : 1;*/

$request_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
$segments = $request_path === '' ? [] : explode('/', $request_path);

$page_action = isset($_GET['page']) ? clean_slug($_GET['page']) : 'home';
$p = isset($_GET['p']) ? max(1, (int) $_GET['p']) : 1;



if (
    isset($segments[0], $segments[1], $segments[2]) &&
    $segments[0] === 'products' &&
    $segments[1] === 'page' &&
    is_numeric($segments[2])
) {
    $page_action = 'products-list';
    $_GET['page'] = 'products-list';
    $_GET['p'] = (int) $segments[2];
    $p = max(1, (int) $segments[2]);
}

if (
    isset($segments[0], $segments[1], $segments[2], $segments[3]) &&
    $segments[0] === 'therapeutic' &&
    $segments[2] === 'page' &&
    is_numeric($segments[3])
) {
    $page_action = 'therapeutic';
    $_GET['page'] = 'therapeutic';
    $_GET['therapy'] = clean_slug($segments[1]);
    $_GET['p'] = (int) $segments[3];
    $p = max(1, (int) $segments[3]);
}

if (
    isset($segments[0], $segments[1], $segments[2], $segments[3]) &&
    $segments[0] === 'product-category' &&
    $segments[2] === 'page' &&
    is_numeric($segments[3])
) {
    $page_action = 'category';
    $_GET['page'] = 'category';
    $_GET['cat'] = clean_slug($segments[1]);
    $_GET['p'] = (int) $segments[3];
    $p = max(1, (int) $segments[3]);
}

$file_prefixes = [
    'ampoule-injections' => 'ampoule',
    'dry-injections' => 'dry',
    'liquid-injections' => 'liquid',
    'pfs-injections' => 'pfs',
    'eye-ear-drops' => 'eye-ear',
    'suspension-injections' => 'suspension',
];

function clean_slug(string $value): string
{
    $value = strtolower(trim($value));
    $value = preg_replace('/[^a-z0-9-]/', '-', $value);
    $value = preg_replace('/-+/', '-', $value);
    return trim($value, '-');
}

function site_url(string $path = ''): string
{
    global $base_url;
    return rtrim($base_url, '/') . '/' . ltrim($path, '/');
}

function canonical_url(string $path = ''): string
{
    return rtrim(site_url($path), '/') . '/';
}

function getCategoryProductsSummary(string $prefix): array
{
    $file = "data/{$prefix}-product.php";

    if (!file_exists($file)) {
        return [];
    }

    require $file;

    return isset($products) && is_array($products) ? $products : [];
}

function getAllProductsSummary(array $file_prefixes): array
{
    $all_products = [];

    foreach ($file_prefixes as $cat_slug => $prefix) {
        $cat_products = getCategoryProductsSummary($prefix);

        foreach ($cat_products as $product) {
            $product['file_prefix'] = $prefix;
            $product['mapped_cat_slug'] = $cat_slug;
            $all_products[] = $product;
        }
    }

    return $all_products;
}

function slugify_text(string $text): string
{
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9-]+/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    return trim($text, '-');
}

function set_404(): void
{
    http_response_code(404);
}

$view = 'pages/404.php';

$page_title = 'Sanjar Pharma - Pharmaceutical Company in India';
$page_description = 'Sanjar Pharma is a trusted pharmaceutical company in Gujarat, India, focused on quality healthcare products with WHO, GLP, GMP and ISO standards.';
$page_keywords = 'Sanjar Pharma, pharmaceutical company India, pharma manufacturer Gujarat, injectable products India';
$page_canonical = canonical_url();
$page_og_image = site_url('assets/images/og/sanjar-pharma-og.jpg');
$page_robots = 'index, follow, max-image-preview:large';
$page_type = 'website';
$schema_file = null;

$meta_title = '';
$meta_description = '';
$meta_image = '';

$is_map_page = in_array($page_action, ['home', 'global-presence'], true);

switch ($page_action) {
    case 'home':
        $latest_blogs = array_slice($blogs, 0, 4);
        $home_categories = $categories;
        $home_therapeutics = $therapeutics;

        $page_title = 'Sanjar Pharma - Pharmaceutical Company in India';
        $page_description = 'Sanjar Pharma is a trusted pharmaceutical company in Gujarat, India, offering quality healthcare products with WHO, GLP, GMP and ISO standards.';
        $page_canonical = canonical_url();
        $page_type = 'website';
        $schema_file = 'home-schema.php';

        $view = 'pages/home.php';
        break;

    case 'about':
    case 'manufacturing':
    case 'global-presence':
    case 'employment':
    case 'contact':
        $page_data = $pages[$page_action] ?? [];

        $page_title = $page_data['seo_title'] ?? ucwords(str_replace('-', ' ', $page_action)) . ' - Sanjar Pharma';
        $page_description = $page_data['seo_desc'] ?? 'Learn more about Sanjar Pharma, a trusted pharmaceutical company based in Gujarat, India.';
        $page_canonical = canonical_url($page_action);
        $page_type = 'website';
        $schema_file = $page_action . '-schema.php';

        $view = "pages/{$page_action}.php";
        break;

    case 'blog-all':
        $total_items = count($blogs);
        $total_pages = max(1, (int) ceil($total_items / $blog_limit));

        if ($p > $total_pages) {
            set_404();
            break;
        }

        $offset = ($p - 1) * $blog_limit;
        $latest_blogs = array_slice($blogs, $offset, $blog_limit);

        $page_title = $p > 1
            ? "Sanjar Pharma Insights - Page {$p}"
            : 'Sanjar Pharma Insights & Pharmaceutical Blog';

        $page_description = 'Read Sanjar Pharma insights on WHO-GMP compliance, sterile manufacturing, injectable products, healthcare quality and pharmaceutical trends.';
        $page_canonical = $p > 1
            ? canonical_url("insights/page/{$p}")
            : canonical_url('insights');

        $page_type = 'website';
        $schema_file = 'insights-schema.php';

        $view = 'pages/blogs.php';
        break;

    case 'blog-single':
        $blog_slug = isset($_GET['slug']) ? clean_slug($_GET['slug']) : '';
        $blog = array_values(array_filter($blogs, static fn($b) => ($b['slug'] ?? '') === $blog_slug))[0] ?? null;

        if (!$blog) {
            set_404();
            break;
        }

        $current_blog = $blog;

        $page_title = $blog['seo_title'] ?? $blog['title'] . ' - Sanjar Pharma';
        $page_description = $blog['seo_desc'] ?? $blog['excerpt'] ?? '';
        $page_canonical = canonical_url($blog['slug']);
        $page_og_image = !empty($blog['image']) ? site_url($blog['image']) : $page_og_image;
        $page_type = 'article';
        $schema_file = 'blog-schema.php';

        $meta_title = $page_title;
        $meta_description = $page_description;
        $meta_image = $page_og_image;

        $view = 'pages/single-blog.php';
        break;

    case 'products-list':
        $all_catalog = getAllProductsSummary($file_prefixes);

        $total_items = count($all_catalog);
        $total_pages = max(1, (int) ceil($total_items / $product_limit));

        if ($p > $total_pages) {
            set_404();
            break;
        }

        $offset = ($p - 1) * $product_limit;
        $display_products = array_slice($all_catalog, $offset, $product_limit);
        $category_data = [];

        $page_title = $p > 1
            ? "Pharmaceutical Product Portfolio - Page {$p}"
            : 'Pharmaceutical Product Portfolio - Sanjar Pharma';

        $page_description = 'Explore Sanjar Pharma pharmaceutical products including sterile SVP injectables, dry powder injections, liquid vials, PFS, ampoules and eye or ear drops.';
        $page_canonical = $p > 1
            ? canonical_url("products/page/{$p}")
            : canonical_url('products');

        $page_og_image = site_url('assets/images/main/hom/liquide.webp');
        $page_type = 'website';
        $schema_file = 'products-schema.php';

        $view = 'pages/products-list.php';
        break;

    case 'category':
        $cat_slug = isset($_GET['cat']) ? clean_slug($_GET['cat']) : '';
        $therapy_filter = isset($_GET['therapy']) ? clean_slug($_GET['therapy']) : null;

        if (file_exists('data/category-details.php')) {
            require_once 'data/category-details.php';
        }

        $current_category = $categories[$cat_slug] ?? null;
        $current_category_details = $category_content[$cat_slug] ?? null;
        $prefix = $file_prefixes[$cat_slug] ?? null;

        if (!$current_category || !$prefix) {
            set_404();
            break;
        }

        $filtered_products = getCategoryProductsSummary($prefix);

        if ($therapy_filter) {
            $filtered_products = array_filter($filtered_products, static function ($product) use ($therapy_filter) {
                if (empty($product['therapeutic_class']) || !is_array($product['therapeutic_class'])) {
                    return false;
                }

                foreach ($product['therapeutic_class'] as $class) {
                    if (slugify_text((string) $class) === $therapy_filter) {
                        return true;
                    }
                }

                return false;
            });
        }

        $total_items = count($filtered_products);
        $total_pages = max(1, (int) ceil($total_items / $product_limit));

        if ($p > $total_pages) {
            set_404();
            break;
        }

        $offset = ($p - 1) * $product_limit;
        $display_products = array_slice($filtered_products, $offset, $product_limit);

        $category_data = $current_category;
        $seo_data = $current_category_details;

        $page_title = $current_category['seo_title'] ?? $current_category['name'] . ' Products - Sanjar Pharma';
        $page_description = $current_category['seo_desc'] ?? 'Explore Sanjar Pharma pharmaceutical products in this category.';
        $page_canonical = $p > 1
            ? canonical_url("product-category/{$cat_slug}/page/{$p}")
            : canonical_url("product-category/{$cat_slug}");

        if ($therapy_filter) {
            $page_canonical = canonical_url("product-category/{$cat_slug}/{$therapy_filter}");
        }

        $page_og_image = !empty($current_category['image']) ? site_url($current_category['image']) : $page_og_image;
        $page_type = 'website';
        $schema_file = 'category-schema.php';

        $view = 'pages/products-list.php';
        break;

    case 'therapeutic':
        $therapy_slug = isset($_GET['therapy']) ? clean_slug($_GET['therapy']) : '';
        $all_catalog = getAllProductsSummary($file_prefixes);

        $filtered_products = array_filter($all_catalog, static function ($product) use ($therapy_slug) {
            if (empty($product['therapeutic_class']) || !is_array($product['therapeutic_class'])) {
                return false;
            }

            foreach ($product['therapeutic_class'] as $class) {
                if (slugify_text((string) $class) === $therapy_slug) {
                    return true;
                }
            }

            return false;
        });

        $total_items = count($filtered_products);
        $total_pages = max(1, (int) ceil($total_items / $product_limit));

        if ($p > $total_pages) {
            set_404();
            break;
        }

        $offset = ($p - 1) * $product_limit;
        $display_products = array_slice($filtered_products, $offset, $product_limit);
        $category_data = [];
        $therapy = ucwords(str_replace('-', ' ', $therapy_slug));

        $page_title = "{$therapy} Pharmaceutical Products - Sanjar Pharma";
        $page_description = "Explore {$therapy} pharmaceutical products by Sanjar Pharma, manufactured with quality-focused pharmaceutical standards.";
        /*$page_canonical = canonical_url("therapeutic/{$therapy_slug}");*/
        $page_canonical = $p > 1
    ? canonical_url("therapeutic/{$therapy_slug}/page/{$p}")
    : canonical_url("therapeutic/{$therapy_slug}");
        $page_type = 'website';
        $schema_file = 'category-schema.php';

        $view = 'pages/products-list.php';
        break;

    case 'product-single':
        $slug = isset($_GET['slug']) ? clean_slug($_GET['slug']) : '';
        $all_products = getAllProductsSummary($file_prefixes);
        $product_summary = array_values(array_filter($all_products, static fn($product) => ($product['slug'] ?? '') === $slug))[0] ?? null;

        if (!$product_summary) {
            set_404();
            break;
        }

        $prefix = $product_summary['file_prefix'];
        $data_file = "data/{$prefix}-product-data.php";

        if (!file_exists($data_file)) {
            set_404();
            break;
        }

        $deep_data_array = require $data_file;
        $product_details = $deep_data_array[$slug] ?? null;

        if (!$product_details) {
            set_404();
            break;
        }

        $product = array_merge($product_summary, $product_details);

        $page_title = $product_summary['seo_title'] ?? $product_summary['name'] . ' - Sanjar Pharma';
        $page_description = $product_summary['seo_desc'] ?? 'View product details, therapeutic class, composition and manufacturing information from Sanjar Pharma.';
        $page_canonical = canonical_url("product/{$slug}");
        $page_og_image = !empty($product_summary['image']) ? site_url($product_summary['image']) : $page_og_image;
        $page_type = 'product';
        $schema_file = 'product-schema.php';

        $meta_title = $page_title;
        $meta_description = $page_description;
        $meta_image = $page_og_image;

        $view = 'pages/product-single.php';
        break;

    case '404':
    default:
        set_404();

        $page_title = 'Page Not Found - Sanjar Pharma';
        $page_description = 'The page you are looking for could not be found on Sanjar Pharma.';
        $page_canonical = canonical_url('404');
        $page_robots = 'noindex, follow';
        $page_type = 'website';
        $schema_file = null;

        $view = 'pages/404.php';
        break;
}

if (!file_exists($view)) {
    set_404();

    $page_title = 'Page Not Found - Sanjar Pharma';
    $page_description = 'The page you are looking for could not be found on Sanjar Pharma.';
    $page_canonical = canonical_url('404');
    $page_robots = 'noindex, follow';
    $schema_file = null;

    $view = 'pages/404.php';
}

require_once 'includes/header.php';
require_once $view;
require_once 'includes/footer.php';