<?php

namespace App\Controllers\Panel;

class BulkJobsPanelController extends PanelController
{
    public function index()
    {
        $this->requireAgency();
        return view('panel/jobs/bulk', $this->panelData(['title' => 'Bulk Job Posting']));
    }

    /**
     * Serves the downloadable CSV template directly (not via the API
     * namespace, since this is a plain file download, not JSON).
     */
    public function template()
    {
        $this->requireAgency();

        $header = ['title', 'description', 'department', 'employment_type', 'experience_level', 'location', 'city', 'country', 'salary_min', 'salary_max', 'education_requirement', 'required_skills', 'is_remote', 'is_hybrid', 'is_visa_sponsorship', 'is_fresh_graduate_ok', 'is_urgent', 'publish'];
        $example = [
            'Senior PHP Developer',
            'We are looking for an experienced PHP developer to join our growing engineering team and help build scalable web applications for our clients.',
            'Engineering',
            'full_time',
            'senior',
            'Lahore, Pakistan',
            'Lahore',
            'Pakistan',
            '120000',
            '180000',
            "Bachelor's degree in Computer Science or related field",
            'PHP;Laravel;MySQL;JavaScript',
            'no',
            'yes',
            'no',
            'no',
            'yes',
            'yes',
        ];

        $csv = implode(',', array_map([$this, 'csvEscape'], $header)) . "\n";
        $csv .= implode(',', array_map([$this, 'csvEscape'], $example)) . "\n";

        return $this->response
            ->setHeader('Content-Type', 'text/csv')
            ->setHeader('Content-Disposition', 'attachment; filename="job-bulk-upload-template.csv"')
            ->setBody($csv);
    }

    private function csvEscape(string $value): string
    {
        if (str_contains($value, ',') || str_contains($value, '"') || str_contains($value, "\n")) {
            return '"' . str_replace('"', '""', $value) . '"';
        }
        return $value;
    }
}
