<?php
error_reporting(E_ALL);
ini_set('display_errors', '0'); // Safe for production across webservers

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include_once __DIR__ . "/lib/service.php";

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

// Ensure required directories exist
$cacheDir = __DIR__ . "/cache";
$cacheDataDir = __DIR__ . "/cache-data";
$cacheDataOldDir = __DIR__ . "/cache-data-old";

foreach ([$cacheDir, $cacheDataDir, $cacheDataOldDir] as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
}

// Maintenance & cache cleanup logic
$ageFile = __DIR__ . "/age.txt";
$folder_time = file_exists($ageFile) ? (int)file_get_contents($ageFile) : 0;
if (time() - 86400 > $folder_time) {
    @file_put_contents($ageFile, time());
    $now = time();

    $files = glob($cacheDir . "/*.*");
    if (is_array($files)) {
        foreach ($files as $file) {
            if (is_file($file) && ($now - filemtime($file) >= 86400 * 7)) {
                @unlink($file);
            }
        }
    }

    $files = glob($cacheDataDir . "/*.*");
    if (is_array($files)) {
        foreach ($files as $file) {
            if (is_file($file) && ($now - filemtime($file) >= 86400 * 30)) {
                $filename = basename($file);
                @rename($file, $cacheDataOldDir . "/{$filename}");
            }
        }
    }
}

// Cache settings
$cache_ext    = '.html';
$cache_time   = 86400; // 24 hours
$cache_folder = $cacheDir . '/';
$ignore_pages = array('', '');

$reqUri = $_SERVER['REQUEST_URI'] ?? '/';
$hostName = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
$dynamic_url  = (defined('PROTOCOL') ? PROTOCOL : 'http') . '://' . $hostName . $reqUri;
$cache_file   = $cache_folder . md5($dynamic_url) . $cache_ext;
$ignore       = in_array($dynamic_url, $ignore_pages);

if ($page === "sitemap" || $page === "sitemap.xml") {
    if (file_exists(__DIR__ . "/sitemap.php")) {
        include_once __DIR__ . "/sitemap.php";
    }
    exit;
}

$mode = "location";
if ($page === "job-company") {
    $page = "job-location";
    $mode = "company";
}

if ($page === "home") {
    $jobData = $service->getDataHome();
    $result  = $jobData;
    $title   = "Home - " . (defined('SITE_TITLE') ? SITE_TITLE : $hostName);
    $desc    = defined('DESCRYPTION') ? DESCRYPTION : '';
} 

if ($page === "job") {
    $jobKeyArr = explode("-", $id);
    $uid = end($jobKeyArr);
    if (defined('ENKRIPSI') && ENKRIPSI == true) {
        $uid = $service->enkrip('decrypt', $uid);
    }
    
    $cache_location = $cacheDataDir . "/{$uid}.json";
    if (file_exists($cacheDataOldDir . "/{$uid}.json")) {
        $cache_location = $cacheDataOldDir . "/{$uid}.json";
    }

    $jobDetail = file_exists($cache_location) ? json_decode(file_get_contents($cache_location), true) : null;

    if ($jobDetail && is_array($jobDetail)) {
        if (!isset($jobDetail["expDate"])) {
            $jobDetail["expDate"] = ($jobDetail["pubDate"] ?? time()) + (86400 * 60);
            @file_put_contents($cache_location, json_encode($jobDetail));
        }

        if (isset($jobDetail["pubDate"]) && $jobDetail["pubDate"] < strtotime('-30 days')) {
            $jobDetail["pubDate"] = time();
            $jobDetail["expDate"] = strtotime('+30 days');
            @file_put_contents($cache_location, json_encode($jobDetail));
        }

        if (isset($jobDetail["expDate"]) && $jobDetail["expDate"] <= time()) {
            $jobDetail["expDate"] = strtotime('+30 days');
            @file_put_contents($cache_location, json_encode($jobDetail));
        }

        $title = ($jobDetail["title"] ?? '') . ' job at ' . ($jobDetail["company"] ?? '') . ' ' . ($jobDetail["location"] ?? '') . ', ' . ($jobDetail["country"] ?? '') . ' - ' . (defined('SITE_TITLE') ? SITE_TITLE : '');
        $desc  = ($jobDetail["title"] ?? '') . ' job at ' . ($jobDetail["company"] ?? '') . ' ' . ($jobDetail["location"] ?? '') . ', ' . ($jobDetail["country"] ?? '') . ' ' . ($jobDetail["sumary"] ?? '');
    } else {
        $title = "Job Detail - " . (defined('SITE_TITLE') ? SITE_TITLE : '');
        $desc  = "Job details not found";
    }

    $sessionArr = is_dir($cacheDataDir) ? array_values(array_diff(scandir($cacheDataDir), array('.', '..'))) : [];
    $result = $service->shuffle_assoc($sessionArr);
} 

if ($page === "job-category" || $page === "job-location" || $page === "job-company") {
    $title = "Browse " . ucwords(str_replace('-', ' ', $id)) . " Jobs - " . (defined('SITE_TITLE') ? SITE_TITLE : '');
    $desc  = "Browse " . ucwords(str_replace('-', ' ', $id)) . " Jobs - " . (defined('SITE_TITLE') ? SITE_TITLE : '');
} 

if (file_exists(__DIR__ . "/header.php")) {
    include_once __DIR__ . "/header.php";
}

if ($page === "job-category") {
    $jobData = $service->ScrapeJooble($id); 
    $result = $jobData;
} 

if ($page === "job-location" || $page === "job-company") {
    if (!file_exists($cache_file) || (file_exists($cache_file) && (time() - filemtime($cache_file) > $cache_time))) {
        $sessionArr = is_dir($cacheDataDir) ? array_values(array_diff(scandir($cacheDataDir), array('.', '..'))) : [];
        if (count($sessionArr) === 0 && is_dir($cacheDataOldDir)) {
            $sessionArr = array_values(array_diff(scandir($cacheDataOldDir), array('.', '..')));
        }
        $result = $service->shuffle_assoc($sessionArr);
    }
} 

$pageFile = __DIR__ . "/{$page}.php";
if (file_exists($pageFile)) {
    include_once $pageFile;
} else {
    include_once __DIR__ . "/home.php";
}

if (file_exists(__DIR__ . "/footer.php")) {
    include_once __DIR__ . "/footer.php";
}
