<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\JobListing;
use App\Models\JobStage;
use App\Services\NotificationService;
use Illuminate\Http\Request;

class JobStageController extends Controller
{
    /**
     * Show stages for a specific job
     */
    public function index(JobListing $job)
    {
        $job->load('stages');
        return view('admin.stages.index', compact('job'));
    }

    /**
     * Edit a stage
     */
    public function edit(JobListing $job, JobStage $stage)
    {
        // Verify stage belongs to this job
        if ($stage->job_listing_id !== $job->id) abort(404);

        return view('admin.stages.form', compact('job', 'stage'));
    }

    /**
     * Update a stage
     */
    public function update(Request $request, JobListing $job, JobStage $stage)
    {
        // Verify stage belongs to this job
        if ($stage->job_listing_id !== $job->id) abort(404);
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'form_fields' => 'nullable|string',
        ]);

        $formFields = null;
        if ($request->form_fields) {
            $formFields = json_decode($request->form_fields, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return back()->withErrors(['form_fields' => 'Format field form tidak valid.'])->withInput();
            }
            // Normalize options: convert comma-separated strings to arrays
            $formFields = $this->normalizeFormFieldOptions($formFields);
        }

        $stage->update([
            'name' => $request->name,
            'description' => $request->description,
            'form_fields' => $formFields,
            'is_active' => $request->has('is_active'),
        ]);

        // Re-sync scheduled notifications (stage name/active status may have changed)
        $synced = app(NotificationService::class)->resyncNotificationsForJob($job);

        return redirect()->route('admin.jobs.stages.index', $job)
            ->with('success', "Tahap \"{$request->name}\" berhasil diperbarui. Notifikasi {$synced} lamaran diperbarui.");
    }

    /**
     * Normalize form field options: convert comma-separated strings to arrays
     */
    private function normalizeFormFieldOptions(?array $fields): ?array
    {
        if (!$fields) return $fields;
        foreach ($fields as &$field) {
            if (isset($field['options']) && is_string($field['options'])) {
                $field['options'] = array_map('trim', explode(',', $field['options']));
            }
        }
        return $fields;
    }

    public function toggle(JobListing $job, JobStage $stage)
    {
        // Verify stage belongs to this job
        if ($stage->job_listing_id !== $job->id) abort(404);

        $stage->update(['is_active' => !$stage->is_active]);

        // Re-sync scheduled notifications (active stages changed)
        app(NotificationService::class)->resyncNotificationsForJob($job);

        return back()->with('success', 'Status tahap berhasil diperbarui. Notifikasi terjadwal disesuaikan.');
    }


}
