﻿<?php

namespace App\Http\Controllers;

use App\Models\RatingType;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;

class RatingTypeController extends Controller
{
    /**
     * Allowed primitive type names.
     * Consider moving this to a config file or an Enum if you prefer.
     */
    public const ALLOWED_TYPES = [
        'percentage',
        'numeric',
        'alphabet',
        'text',
        'custom',
    ];

    /* -----------------------------------------------------------------
     | Index – list all rating types belonging to the current org
     |-----------------------------------------------------------------*/
    public function index()
    {
        $orgId = Auth::user()->organisation_id;

        $ratingTypes = RatingType::where('organisation_id', $orgId)
            ->latest()
            ->paginate(15);

        return view('rating_types.index', compact('ratingTypes'));
    }

    /* -----------------------------------------------------------------
     | Create – show the new-rating-type form
     |-----------------------------------------------------------------*/
    public function create()
    {
        $typeOptions = ['' => 'Select Type'] + array_combine(self::ALLOWED_TYPES, array_map('ucwords', self::ALLOWED_TYPES));
        return view('rating_types.create', [
            'types' => $typeOptions,
        ]);
    }

    /* -----------------------------------------------------------------
     | Store – persist a brand-new rating type
     |-----------------------------------------------------------------*/
    public function store(Request $request)
    {
        $data = $this->validateData($request);

        $data['organisation_id'] = Auth::user()->organisation_id;

        RatingType::create($data);

        return redirect()
            ->route('rating-types.index')
            ->with('success', 'Rating type created successfully.');
    }

    /* -----------------------------------------------------------------
     | Edit – show the edit form
     |-----------------------------------------------------------------*/
    public function edit(RatingType $ratingType)
    {
        $this->authorizeOrg($ratingType);

        $typeOptions = ['' => 'Select Type'] + array_combine(self::ALLOWED_TYPES, array_map('ucwords', self::ALLOWED_TYPES));

        return view('rating_types.edit', [
            'ratingType' => $ratingType,
            'types'      => $typeOptions,
        ]);
    }

    /* -----------------------------------------------------------------
     | Update – persist changes
     |-----------------------------------------------------------------*/
    public function update(Request $request, RatingType $ratingType)
    {
        $this->authorizeOrg($ratingType);

        $data = $this->validateData($request, $ratingType->id);

        $ratingType->update($data);

        return redirect()
            ->route('rating-types.index')
            ->with('success', 'Rating type updated successfully.');
    }

    /* -----------------------------------------------------------------
     | Destroy – delete the rating type
     |-----------------------------------------------------------------*/
    public function destroy(RatingType $ratingType)
    {
        $this->authorizeOrg($ratingType);

        $ratingType->delete();

        return redirect()
            ->route('rating-types.index')
            ->with('success', 'Rating type deleted.');
    }

    /* -----------------------------------------------------------------
     | Private helpers
     |-----------------------------------------------------------------*/

    /**
     * Centralised validator so store / update share identical rules.
     */
    protected function validateData(Request $request, ?int $id = null): array
    {
        return $request->validate([
            'name'                   => ['required', 'string', 'max:100'],
            'type'                   => ['required', Rule::in(self::ALLOWED_TYPES)],
            'config'                 => ['nullable', 'json'],
            'is_required'            => ['sometimes', 'boolean'],
            'is_weighted'            => ['sometimes', 'boolean'],
            'is_default'             => ['sometimes', 'boolean'],
            'is_visible_to_employee' => ['sometimes', 'boolean'],
        ]);
    }

    /**
     * Simple guard so one organisation cannot tamper with another’s rating types.
     */
    protected function authorizeOrg(RatingType $ratingType): void
    {
        if ($ratingType->organisation_id !== Auth::user()->organisation_id) {
            abort(403, 'Unauthorized');
        }
    }