<?php

namespace App\Http\Controllers\Employee;

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

class PersonalityController extends Controller
{
    public function index(): View
    {
        // * Get all personalities ordered by personality_code ascending
        $personalities = Personality::with('career')->orderBy('personality_code', 'asc')->get();

        return view('employee.pages.personality.index', compact('personalities'));
    }

    public function generatePersonalityCode(): string
    {
        // * Get the latest personality ordered by personality_code descending
        $latestPersonality = Personality::orderBy('personality_code', 'desc')->first();

        // * If there is no personality, the next personality code will be P001
        if (!$latestPersonality) {
            $nextPersonalityCode = 'P0001';

            // * If there is a personality, the next personality code will be the latest personality code + 1
        } else {
            $latestPersonalityCode = $latestPersonality->personality_code;
            $number = (int) substr($latestPersonalityCode, 1);
            $nextNumber = $number + 1;
            $nextPersonalityCode = 'P' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);
        }

        return $nextPersonalityCode;
    }

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

        // * Get all careers ordered by career_code ascending
        $careers = Career::orderBy('career_code', 'asc')->get();

        return view('employee.pages.personality.create', compact('generatePersonalityCode', 'careers'));
    }

    public function store(PersonalityRequest $request): RedirectResponse
    {
        // * Create the personality
        $personality = Personality::create([
            'personality_code' => $request->personality_code,
            'personality' => $request->personality,
            'slug' => Str::slug($request->personality),
            'desc' => $request->desc,
        ]);

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

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

        // * Sync the careers to the personality
        $personality->career()->sync($request->careers);

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

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

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

        // * Get the selected career ids
        $selectedCareerIds = $personalities->career()->pluck('careers.id')->toArray();

        return view('employee.pages.personality.edit', compact('personalities', 'careers', 'selectedCareerIds'));
    }

    public function update(PersonalityRequest $request, Personality $personalities): RedirectResponse
    {
        // * Update the personality
        $personalities->update([
            'personality_code' => $request->personality_code,
            'personality' => $request->personality,
            'slug' => Str::slug($request->personality),
            'desc' => $request->desc,
        ]);

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

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

        // * Sync the careers to the personality
        $personalities->career()->sync($request->careers);

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

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

    public function reorderPersonalityCode(): void
    {
        // * Get all personalities ordered by personality_code ascending
        $personalityCode = Personality::orderBy('personality_code', 'asc')->get();

        // * Reorder the personality code
        foreach ($personalityCode as $index => $personality) {
            $personality->update([
                'personality_code' => 'P' . str_pad($index + 1, 4, '0', STR_PAD_LEFT),
            ]);
        }
    }

    public function destroy(Personality $personalities): RedirectResponse
    {
        // * Delete the personality
        $personalities->delete();

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

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

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