<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Employee;
use App\Models\GoalType;
use App\Models\Indicator;
use App\Models\Competencies;
use App\Models\GoalTracking;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\Performance_Type;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;


class GoalTrackingController extends Controller
{

    public function index()
    {
        if (Auth::user()->can('Manage Goal Tracking')) {
            $user = Auth::user();
            if ($user->type == 'employee') {
                $employee      = Employee::where('user_id', $user->id)->first();
                $goalTrackings = GoalTracking::where('created_by', '=', Auth::user()->creatorId())->where('branch', $employee->branch_id)->get();
            } else {
                $goalTrackings = GoalTracking::where('created_by', '=', Auth::user()->creatorId())->with('goalType')->get();
            }

            return view('goaltracking.index', compact('goalTrackings'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function create()
    {
        if (Auth::user()->can('Create Goal Tracking')) {

            $user = Auth::user();
            $organisationId = $user->organisation_id;

            // Branches
            $brances = Branch::where('created_by', $user->creatorId())
                ->pluck('name', 'id')
                ->prepend('Select Branch', '');

            // Goal Types
            $goalTypes = GoalType::where('created_by', $user->creatorId())
                ->pluck('name', 'id')
                ->prepend('Select Goal Type', '');

            // Employee details
            $employee = Employee::where('user_id', $user->id)->first();

            // Get indicators from department
            $rawIndicators = Indicator::where('department', $employee->department_id)->get();

            // Build indicator dropdown: key = id, value = label from performance_type names
            $indicators = $rawIndicators->mapWithKeys(function ($indicator) {
                $ratings = json_decode($indicator->rating, true);

                // Fetch performance type names
                $performanceTypes = Performance_Type::whereIn('id', array_keys($ratings))
                    ->pluck('name')
                    ->toArray();

                // If no names found, fallback
                $label = count($performanceTypes)
                    ? 'Indicator (' . implode(', ', $performanceTypes) . ')'
                    : 'Indicator #' . $indicator->id;

                return [$indicator->id => $label];
            });

            $previousGoals = GoalTracking::where('created_by', $user->creatorId())
                ->orderBy('id', 'desc')
                ->get(['id', 'subject']);


            return view('goaltracking.create', compact(
                'brances',
                'goalTypes',
                'indicators',
                'previousGoals'
            ));
        }

        return redirect()->back()->with('error', __('Permission denied.'));
    }

    public function fetchPreviousGoal($id)
    {
        $goal = GoalTracking::findOrFail($id);

        return response()->json([
            'branch' => $goal->branch,
            'goal_type' => $goal->goal_type,
            'start_date' => $goal->start_date,
            'end_date' => $goal->end_date,
            'subject' => $goal->subject,
            'target_achievement' => $goal->target_achievement,
            'description' => $goal->description,
        ]);
    }


    public function getCompetenciesByIndicator($indicatorId)
    {
        $indicator = Indicator::find($indicatorId);

        Log::info("rr", [$indicator]);
        if (!$indicator || empty($indicator->rating)) {
            return response()->json([]);
        }
        $ratingIds = array_keys(json_decode($indicator->rating, true));

        $performanceTypes = Performance_Type::with('types')
            ->whereIn('id', $ratingIds)
            ->get();

        $competencies = [];

        foreach ($performanceTypes as $type) {
            foreach ($type->types as $comp) {
                $competencies[] = [
                    'id' => $comp->id,
                    'name' => $comp->name,
                ];
            }
        }

        return response()->json($competencies);
    }


    public function store(Request $request)
    {
        if (\Auth::user()->can('Create Goal Tracking')) {

            $validator = \Validator::make(
                $request->all(),
                [
                    'branch' => 'required',
                    'goal_type' => 'required',
                    'start_date' => 'required',
                    'end_date' => 'required|after_or_equal:start_date',
                    'subject' => 'required',
                    'goal_scope' => 'required|in:individual,department',
                ]
            );
            if ($validator->fails()) {
                $messages = $validator->getMessageBag();

                return redirect()->back()->with('error', $messages->first());
            }

            $goalTracking                     = new GoalTracking();
            $goalTracking->branch             = $request->branch;
            $goalTracking->goal_type          = $request->goal_type;
            $goalTracking->start_date         = $request->start_date;
            $goalTracking->end_date           = $request->end_date;
            $goalTracking->subject            = $request->subject;
            $goalTracking->target_achievement = $request->target_achievement;
            $goalTracking->description        = $request->description;
            $goalTracking->created_by         = \Auth::user()->creatorId();
            $goalTracking->goal_scope = $request->goal_scope;
            $goalTracking->save();


            // Attach indicators and competencies if applicable
            if ($request->has('indicators')) {
                $goalTracking->indicators()->sync($request->indicators);
            }

            if ($request->has('competencies')) {
                $goalTracking->competencies()->sync($request->competencies);
            }


            return redirect()->route('goaltracking.index')->with('success', __('Goal tracking successfully created.'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function show(GoalTracking $goalTracking)
    {
        //
    }


    public function edit($id)
    {
        if (\Auth::user()->can('Edit Goal Tracking')) {
            // Load goal tracking with relationships
            $goalTracking = GoalTracking::with(['indicators', 'competencies'])->find($id);

            if (!$goalTracking) {
                return redirect()->back()->with('error', __('Goal tracking not found.'));
            }

            // Branches
            $brances = Branch::where('created_by', '=', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $brances->prepend('Select Branch', '');

            // Goal Types
            $goalTypes = GoalType::where('created_by', '=', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $goalTypes->prepend('Select Goal Type', '');

            // Get current user's employee record to find department
            $user = \Auth::user();
            $employee = Employee::where('user_id', $user->id)->first();

            // Get indicators for this employee's department
            $indicators = collect();
            if ($employee && $employee->department_id) {
                $rawIndicators = Indicator::where('department', $employee->department_id)->get();

                $indicators = $rawIndicators->mapWithKeys(function ($indicator) {
                    $ratings = json_decode($indicator->rating, true) ?: [];

                    $performanceTypes = Performance_Type::whereIn('id', array_keys($ratings))
                        ->pluck('name')
                        ->toArray();

                    $label = count($performanceTypes)
                        ? 'Indicator (' . implode(', ', $performanceTypes) . ')'
                        : 'Indicator #' . $indicator->id;

                    return [$indicator->id => $label];
                });
            }

            // Prepend default option
            $indicators->prepend('Select Indicator', '');

            // Get selected indicator ID (first one if multiple exist)
            $selectedIndicatorId = $goalTracking->indicators->first()->id ?? null;

            // Get selected competency IDs
            $selectedCompetencyIds = $goalTracking->competencies->pluck('id')->toArray();

            // Status options
            $status = GoalTracking::$status;

            return view('goaltracking.edit', compact(
                'brances',
                'goalTypes',
                'goalTracking',
                'status',
                'indicators',
                'selectedIndicatorId',
                'selectedCompetencyIds'
            ));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function update(Request $request, $id)
    {
        if (\Auth::user()->can('Edit Goal Tracking')) {
            $goalTracking = GoalTracking::find($id);
            $validator    = \Validator::make(
                $request->all(),
                [
                    'branch' => 'required',
                    'goal_type' => 'required',
                    'start_date' => 'required',
                    'end_date' => 'required',
                    'subject' => 'required',
                ]
            );
            if ($validator->fails()) {
                $messages = $validator->getMessageBag();

                return redirect()->back()->with('error', $messages->first());
            }

            $goalTracking->branch             = $request->branch;
            $goalTracking->goal_type          = $request->goal_type;
            $goalTracking->start_date         = $request->start_date;
            $goalTracking->end_date           = $request->end_date;
            $goalTracking->subject            = $request->subject;
            $goalTracking->target_achievement = $request->target_achievement;
            $goalTracking->status             = $request->status;
            $goalTracking->progress           = $request->progress;
            $goalTracking->description        = $request->description;
            $goalTracking->rating             = $request->rating;
            $goalTracking->goal_scope = $request->goal_scope;

            $goalTracking->save();

            return redirect()->route('goaltracking.index')->with('success', __('Goal tracking successfully updated.'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function destroy($id)
    {
        if (\Auth::user()->can('Delete Goal Tracking')) {
            $goalTracking = GoalTracking::find($id);
            if ($goalTracking->created_by == \Auth::user()->creatorId()) {
                $goalTracking->delete();

                return redirect()->route('goaltracking.index')->with('success', __('GoalTracking successfully deleted.'));
            } else {
                return redirect()->back()->with('error', __('Permission denied.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }

    public function markGoalAsApproved(Request $request)
    {
        if (\Auth::user()->can('Edit Goal Tracking')) {
            $goalTracking = GoalTracking::find($id);
            $validator    = \Validator::make(
                $request->all(),
                [
                    'is_approved' => 'required',
                ]
            );
            if ($validator->fails()) {
                $messages = $validator->getMessageBag();

                return redirect()->back()->with('error', $messages->first());
            }

            $goalTracking->is_approved             = $request->is_approved;
            $goalTracking->save();

            return redirect()->route('goaltracking.index')->with('success', __('Goal approved successfully.'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }
}
