<?php

namespace App\Http\Controllers\Employee;

use App\Models\Career;
use Illuminate\View\View;
use App\Models\Department;
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Employee\CareerRequest;

class CareerController extends Controller
{
    public function index(): View
    {
        // * Get all careers ordered by career_code ascending
        $careers = Career::orderBy('career_code', 'asc')->get();

        return view('employee.pages.career.index', compact('careers'));
    }

    public function generateCareerCode(): string
    {
        // * Get the latest career ordered by career_code descending
        $latestCareer = Career::orderBy('career_code', 'desc')->first();

        // * If there is no career, the next career code will be C0001
        // * If there is a career, the next career code will be the latest career code + 1
        if (!$latestCareer) {
            $nextCareerCode = 'C0001';
        } else {
            $latestCareerCode = $latestCareer->career_code;
            $number = (int) substr($latestCareerCode, 1);
            $nextNumber = $number + 1;
            $nextCareerCode = 'C' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);
        }

        return $nextCareerCode;
    }

    public function create(): View
    {
        // * Generate the career code
        $generateCareerCode = $this->generateCareerCode();

        // * Get all departments ordered by department_name ascending
        $departments = Department::orderBy('department_name', 'asc')->get();

        return view('employee.pages.career.create', compact('generateCareerCode', 'departments'));
    }

    public function store(CareerRequest $request): RedirectResponse
    {
        // * Create the career
        $career = Career::create([
            'career_code' => $request->career_code,
            'career_title' => $request->career_title,
            'slug' => Str::slug($request->career_title),
            'career_description' => $request->career_description,
            'is_specific' => $request->is_specific
        ]);

        if ($request->hasFile('image_url')) {
            $filename = time() . '_' . uniqid() . '.' . $request->image_url->getClientOriginalExtension();
            $path = $request->image_url->storeAs('public/illustrations', $filename);
            $imageUrl = Storage::url($path);

            $career->image_url = $filename;
            $career->save();
        }

        // * Sync the career with the departments
        $career->departments()->sync($request->departments);

        // * Notification
        $notification = [
            'message' => 'Karier telah berhasil ditambahkan',
            'alert-type' => 'info',
        ];

        return redirect()->route('careers')->with($notification);
    }

    public function edit(Career $careers): View
    {
        // * Get all departments ordered by department_name ascending
        $departments = Department::orderBy('department_name', 'asc')->get();

        // * Get the selected department ids
        $selectedDepartmentIds = $careers->departments()->pluck('departments.id')->toArray();

        return view('employee.pages.career.edit', compact('careers', 'departments', 'selectedDepartmentIds'));
    }

    public function update(CareerRequest $request, Career $careers): RedirectResponse
    {
        // * Update the career
        $careers->update([
            'career_code' => $request->career_code,
            'career_title' => $request->career_title,
            'slug' => Str::slug($request->career_title),
            'career_description' => $request->career_description,
            'is_specific' => $request->is_specific
        ]);

        if ($request->hasFile('image_url')) {
            $filename = time() . '_' . uniqid() . '.' . $request->image_url->getClientOriginalExtension();
            $path = $request->image_url->storeAs('public/illustrations', $filename);
            $imageUrl = Storage::url($path);

            $careers->image_url = $filename;
            $careers->save();
        }

        // * Sync the career with the departments
        $careers->departments()->sync($request->departments);

        // * Notification
        $notification = [
            'message' => 'Karier telah berhasil diperbarui',
            'alert-type' => 'info',
        ];

        return redirect()->route('careers')->with($notification);
    }

    public function reorderPersonalityCode(): void
    {
        // * Get all careers ordered by career_code ascending
        $careerCode = Career::orderBy('career_code', 'asc')->get();

        // * Reorder the career code
        foreach ($careerCode as $index => $career) {
            $career->update([
                'career_code' => 'C' . str_pad($index + 1, 4, '0', STR_PAD_LEFT),
            ]);
        }
    }

    public function destroy(Career $careers): RedirectResponse
    {
        // * Delete the career
        $careers->delete();

        // * Reorder the career code
        $this->reorderPersonalityCode();

        // * Notification
        $notification = [
            'message' => 'Karier telah berhasil dihapus',
            'alert-type' => 'info',
        ];

        return redirect()->route('careers')->with($notification);
    }
}
