include_once("load_external_chart_data.php");
include_once("merged_jobs_feed.php");


$jobsBySource = fetchJobsBySource();
$html = "";

foreach ($jobsBySource as $source => $jobList) {
    if (empty($jobList)) continue;
		
		 $sourceSlug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $source));
    $sourceSlug = getSourceSlug($source);
    $html .= "<h3 id='section--{$sourceSlug}' style='text-align:center; margin-top:30px;'>🌍 " . htmlspecialchars($source) . "</h3>";
    $html .= "<div class='jobs-grid'>";

    foreach ($jobList as $job) {
        $sourceSlug = getSourceSlug($job['source']);
        $cardClass = 'job-card';

        // Determine expiry status
        $isExpired = false;
        $closingSoon = false;
        $formattedDate = '';
        $daysRemaining = null;

        if (!empty($job['expiry_date'])) {
            $rawDate = $job['expiry_date'];
            if (is_numeric($rawDate)) {
                if ($rawDate > 9999999999) $rawDate = $rawDate / 1000;
                $formattedDate = date("d M Y", (int)$rawDate);
                $daysRemaining = floor(($rawDate - time()) / 86400);
                $closingSoon = $daysRemaining <= 7 && $daysRemaining > 0;
                $isExpired = $daysRemaining < 0;
            } else {
                $formattedDate = htmlspecialchars($rawDate);
            }
        }

        if ($isExpired) $cardClass .= " expired-card";

        $html .= "<div class='{$cardClass} card-{$sourceSlug}'>";
        $html .= "<h3>" . htmlspecialchars($job['title']) . "</h3>";

        switch ($job['source']) {
            case 'Govt': $label = 'Government'; break;
            case 'PJN': $label = 'Pacific Vacancies'; break;
            case 'SPREP':
            case 'SPC':
            case 'PIFS':
            case 'FFA':
            case 'UNDP': $label = 'Organization'; break;
            default: $label = 'Employer';
        }

        $html .= "<p><strong>{$label}:</strong> " . htmlspecialchars($job['company']) . "</p>";
        $html .= "<p><strong>Type:</strong> " . htmlspecialchars($job['type']) . "</p>";

        $locationFull = htmlspecialchars($job['location']);
        $hasMoreLocation = mb_strlen($locationFull) > 100;
        $locationPreview = mb_substr($locationFull, 0, 100);

        $html .= "<p><strong>Location:</strong> ";
        if ($hasMoreLocation) {
            $html .= "<span class='location-preview'>{$locationPreview}...</span><span class='location-full' style='display:none;'>{$locationFull}</span><a href='javascript:void(0)' class='toggle-location' onclick='toggleLocation(this)'>Read more</a>";
        } else {
            $html .= $locationFull;
        }
        $html .= "</p>";

        $html .= "<p><strong>Expires:</strong> {$formattedDate}";
        if ($isExpired) {
            $daysSinceExpiry = abs($daysRemaining);
            if ($daysSinceExpiry <= 7) {
                $left = 7 - $daysSinceExpiry;
                $html .= " <span class='grace-message'>🔒 Expired — waiting for possible extension. Auto-archiving in {$left} day" . ($left != 1 ? "s" : "") . ".</span>";
            } else {
                $html .= " <span class='expired-tag'>🔒 Expired</span>";
            }
        } elseif ($closingSoon) {
            $daysLabel = $daysRemaining == 1 ? "day" : "days";
            $html .= " <span class='closing-soon-animated'>🔴 Closing in {$daysRemaining} {$daysLabel}</span>";
        }
        $html .= "</p>";

        $descFull = htmlspecialchars($job['excerpt_full']);
        $hasMoreDesc = mb_strlen($descFull) > 160;
        $descPreview = mb_substr($descFull, 0, 160);

        if (!empty(trim($descFull))) {
            $html .= "<p><strong>Description:</strong><br>";
            if ($hasMoreDesc) {
                $html .= "<span class='desc-preview'>{$descPreview}...</span><span class='desc-full' style='display:none;'>{$descFull}</span><a href='javascript:void(0)' class='toggle-desc' onclick='toggleDescription(this)'>Read more</a>";
            } else {
                $html .= $descFull;
            }
            $html .= "</p>";
        }

        $html .= "<a class='view-job-btn' href='track_remote_click.php?url=" . urlencode($job['url']) . "&title=" . urlencode($job['title']) . "&company=" . urlencode($job['company']) . "' target='_blank'>View Job</a>";

        $encouragements = [
            "🚀 Your moment is now — make the leap!",
            "💪 You've got what it takes. Let’s go!",
            "🌱 Every expert was once a beginner.",
            "🔥 Shine bright, this could be your spark.",
            "💡 Opportunity knocks. Open the door.",
            "📈 Ready to grow your career?",
            "🎯 You’re closer than you think!",
            "🌟 This could be your breakout role.",
            "🛠️ Skills ready. Time to apply!",
            "🎓 Learning never stops — go for it.",
            "🌍 New challenges bring new rewards.",
            "🏆 You deserve this opportunity.",
            "💬 Apply confidently — your voice matters.",
            "🎉 You’re qualified. Celebrate the chance.",
            "💖 Your passion shines — show them.",
            "🧠 Smart, driven, and ready to lead.",
            "📌 This could be your next adventure.",
            "📚 Every job teaches — what will you learn?",
            "💼 Time to upgrade your story.",
            "🧭 Trust your direction.",
            "🪄 Believe in your magic — apply now.",
            "🎯 A great match is one click away.",
            "🌟 Go where your skills are valued.",
            "🌈 This role may open new doors.",
            "✈️ Don’t just dream it — do it.",
            "🧗 Take the step. You’re ready.",
            "🎬 Time to take the lead role.",
            "⚡ Spark change with your ideas.",
            "📣 You bring the energy they need.",
            "💎 Your talent is rare — use it.",
            "🔍 This could be your perfect fit.",
            "🥇 Every win starts with an attempt.",
            "🌻 Let your growth bloom here.",
            "🏁 Why wait? Start your journey.",
            "🧳 Pack your strengths and go!",
            "🎵 This could be your rhythm.",
            "🏗️ Build your future brick by brick.",
            "🧩 You complete the puzzle.",
            "🕊️ Set your career free.",
            "🛎️ It’s your time to answer the call.",
            "🪴 Plant your potential here.",
            "🧬 You’re made for this.",
            "🌐 Let the world see your worth.",
            "💬 Every story needs a voice — yours.",
            "⚙️ The right role makes all the difference.",
            "📍 Find purpose in your path.",
            "🧠 Bring your best ideas forward.",
            "🎯 Aim high. You’re ready.",
            "🎓 This could be your real-world degree.",
            "🏄 Ride the wave — don't miss out."
        ];

        $random_tip = $encouragements[array_rand($encouragements)];
        $html .= "<div class='card-hover-tip'><span class='close-tip' onclick='this.parentElement.style.display=\"none\"' title='Dismiss tip'>✖</span>{$random_tip}</div>";

        $html .= "</div>"; // Close job-card
    }
    $html .= "</div>"; // Close jobs-grid
}

$xt->assign("external_jobs", $html);

// Handle AJAX refresh
if (postvalue("ajax_remote_jobs") == "1") {
    echo $xt->fetchVar("external_jobs");
    exit();
}


//____________________________________________________________________________________________________________

// 📊 Prepare chart data for User-Posted Jobs flip card
$user_active = DB::Lookup("SELECT COUNT(*) FROM jobsjobs WHERE COALESCE(extended_due_date, due_date) > CURDATE()");
$user_expired7 = DB::Lookup("
    SELECT COUNT(*) FROM jobsjobs
    WHERE COALESCE(extended_due_date, due_date) <= CURDATE()
      AND COALESCE(extended_due_date, due_date) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
");
$user_archived = DB::Lookup("
    SELECT COUNT(*) FROM jobsjobs
    WHERE COALESCE(extended_due_date, due_date) < DATE_SUB(CURDATE(), INTERVAL 7 DAY)
");

// Assign raw values for JS use
$xt->assign("user_active_raw", $user_active);
$xt->assign("user_expired7_raw", $user_expired7);
$xt->assign("user_archived_raw", $user_archived);

// Assign formatted values for HTML display
$xt->assign("user_active", number_format($user_active) . " Active");
$xt->assign("user_expired7", number_format($user_expired7) . " Expired (7d)");
$xt->assign("user_archived", number_format($user_archived) . " Archived");

//new chart
$trendSql = "
    SELECT 
        DATE_FORMAT(DateAdded, '%Y-%m') AS month,
        source,
        COUNT(*) AS job_count
    FROM external_jobs
    WHERE DateAdded >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    GROUP BY month, source
    ORDER BY month ASC
";

$trendData = [];
$months = [];
$sources = [];

$rs = DB::Query($trendSql);
while ($row = $rs->fetchAssoc()) {
    $month = $row['month'];
    $source = $row['source'];
    $count = (int)$row['job_count'];

    $trendData[$source][$month] = $count;
    $months[$month] = true;
    $sources[$source] = true;
}

// Normalize months (fill 0 for missing months)
$labels = array_keys($months);
sort($labels);

$datasets = [];
$colors = ['#4caf50', '#2196f3', '#ff9800', '#e91e63', '#9c27b0', '#3f51b5', '#00bcd4', '#009688'];
$colorIndex = 0;

foreach ($sources as $source => $_) {
    $data = [];
    foreach ($labels as $month) {
        $data[] = isset($trendData[$source][$month]) ? $trendData[$source][$month] : 0;
    }
    $datasets[] = [
        'label' => $source,
        'data' => $data,
        'borderColor' => $colors[$colorIndex++ % count($colors)],
        'fill' => false,
        'tension' => 0.3
    ];
}

$xt->assign("line_chart_labels", json_encode($labels));
$xt->assign("line_chart_datasets", json_encode($datasets));
