<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\Goal;
use App\Models\User;
use App\Support\FormTextRules;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class GoalController extends Controller
{
    public function index()
    {
        $goals = Goal::latest()->paginate(12);

        return view('performance.goals.index', compact('goals'));
    }

    public function create()
    {
        $departments = Department::orderBy('name')->get();
        $users = $this->tenantUsers();

        return view('performance.goals.create', compact('departments', 'users'));
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $validated = $request->validate($this->goalRules(), FormTextRules::messages());

        Goal::create(array_merge($validated, [
            'company_id' => $companyId,
        ]));

        return redirect()->route('goals.index')->with('success', 'Goal created successfully.');
    }

    public function edit(Goal $goal)
    {
        $departments = Department::orderBy('name')->get();
        $users = $this->tenantUsers();

        return view('performance.goals.edit', compact('goal', 'departments', 'users'));
    }

    public function update(Request $request, Goal $goal)
    {
        $validated = $request->validate($this->goalRules(), FormTextRules::messages());
        $goal->update($validated);

        return redirect()->route('goals.index')->with('success', 'Goal updated successfully.');
    }

    public function destroy(Goal $goal)
    {
        $goal->delete();

        return redirect()->route('goals.index')->with('success', 'Goal deleted successfully.');
    }

    /**
     * @return array<string, mixed>
     */
    protected function goalRules(): array
    {
        return [
            'title' => FormTextRules::notNumericOnly(true, 191),
            'team' => FormTextRules::notNumericOnly(false, 191),
            'description' => FormTextRules::notNumericOnly(false, 5000),
            'user_id' => ['required', 'exists:users,id'],
            'department_id' => ['required', 'exists:departments,id'],
            'progress' => ['required', 'integer', 'min:0', 'max:100'],
            'target' => ['required', 'string', 'max:191'],
            'due_date' => ['nullable', 'date'],
            'status' => ['required', Rule::in(['on_track', 'at_risk', 'behind', 'completed'])],
        ];
    }

    private function tenantUsers()
    {
        $currentUser = Auth::user();
        $users = User::query()->forActiveDirectory();

        if ($currentUser?->company_id) {
            $users->where('company_id', $currentUser->company_id);
        }

        return $users->orderBy('name')->get();
    }
}
