<?php

namespace App\Controllers;

use App\Models\JobModel;
use Config\Database;

class JobDetailController extends BaseController
{
    public function show(string $slug)
    {
        $job = (new JobModel())
            ->select('jobs.*, agencies.company_name, agencies.logo_path, agencies.verification_status, agencies.description as agency_description, owner.username as agency_username,
                (SELECT COUNT(*) FROM job_applications WHERE job_applications.job_id = jobs.id) as applicant_count')
            ->join('agencies', 'agencies.id = jobs.agency_id')
            ->join('users as owner', 'owner.id = agencies.owner_user_id')
            ->where('jobs.seo_slug', $slug)
            ->where('jobs.status', 'published')
            ->first();

        if (! $job) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        (new JobModel())->incrementViews($job->id);

        $skills = [];
        if ($job->required_skills) {
            $skills = is_string($job->required_skills) ? json_decode($job->required_skills, true) : $job->required_skills;
        }

        $viewerLoggedIn = (bool) session()->get('user_id');
        $viewerIsCandidate = session()->get('role') === 'candidate';

        // Has this candidate already applied? Only meaningful if logged in
        // as a candidate — used to swap the Apply button for "Applied".
        $alreadyApplied = false;
        if ($viewerIsCandidate) {
            $profile = Database::connect()->table('candidate_profiles')->where('user_id', session()->get('user_id'))->get()->getRowArray();
            if ($profile) {
                $alreadyApplied = Database::connect()->table('job_applications')
                    ->where('job_id', $job->id)->where('candidate_profile_id', $profile['id'])
                    ->countAllResults() > 0;
            }
        }

        // Similar jobs (same category, excluding this one) for a bit of
        // "keep browsing" continuity — small, non-critical enhancement.
        $similarJobs = (new JobModel())
            ->select('jobs.id, jobs.title, jobs.seo_slug, jobs.location, agencies.company_name')
            ->join('agencies', 'agencies.id = jobs.agency_id')
            ->where('jobs.status', 'published')
            ->where('jobs.id !=', $job->id)
            ->groupStart()
                ->where('jobs.category_id', $job->category_id)
                ->orWhere('jobs.employment_type', $job->employment_type)
            ->groupEnd()
            ->limit(5)
            ->find();

        return view('public/job_detail', [
            'title'           => $job->title . ' at ' . $job->company_name . ' | Job Portal',
            'metaDescription' => mb_substr(strip_tags($job->description), 0, 160),
            'job'             => $job,
            'skills'          => $skills,
            'viewerLoggedIn'  => $viewerLoggedIn,
            'viewerIsCandidate' => $viewerIsCandidate,
            'alreadyApplied'  => $alreadyApplied,
            'similarJobs'     => $similarJobs,
            'jsonLd'          => $this->jobJsonLd($job, $skills),
        ]);
    }

    private function jobJsonLd($job, array $skills): string
    {
        $schema = [
            '@context'    => 'https://schema.org',
            '@type'       => 'JobPosting',
            'title'       => $job->title,
            'description' => strip_tags($job->description),
            'datePosted'  => is_object($job->created_at) ? $job->created_at->format('Y-m-d') : substr((string) $job->created_at, 0, 10),
            'employmentType' => strtoupper($job->employment_type),
            'hiringOrganization' => [
                '@type' => 'Organization',
                'name'  => $job->company_name,
            ],
            'jobLocation' => [
                '@type' => 'Place',
                'address' => $job->location ?: ($job->city ?: 'Remote'),
            ],
        ];

        if ($job->salary_min || $job->salary_max) {
            $schema['baseSalary'] = [
                '@type'    => 'MonetaryAmount',
                'currency' => $job->salary_currency ?: 'PKR',
                'value'    => [
                    '@type'   => 'QuantitativeValue',
                    'minValue' => $job->salary_min,
                    'maxValue' => $job->salary_max,
                    'unitText' => 'MONTH',
                ],
            ];
        }

        return json_encode($schema, JSON_UNESCAPED_SLASHES);
    }
}
