<?php

namespace App\Http\Controllers;

use App\Models\Appraisal;
use App\Models\Branch;
use App\Models\Competencies;
use App\Models\Department;
use App\Models\Employee;
use App\Models\Indicator;
use App\Models\Performance_Type;
use App\Models\Designation;
use Illuminate\Http\Request;

class AppraisalController extends Controller
{

    public function index(Request $request)
    {
        if (\Auth::user()->can('Manage Appraisal')) {
            $user = \Auth::user();
            $competencyCount = Competencies::where('created_by', '=', $user->creatorId())->count();

            $query = Appraisal::where('created_by', '=', $user->creatorId());

            if ($user->type == 'employee') {
                $employee = Employee::where('user_id', $user->id)->first();
                $query->where('branch', $employee->branch_id)
                    ->where('employee', $employee->id);
            }

            // Apply date filter
            if (!empty($request->start_date)) {
                $query->whereDate('created_at', '>=', $request->start_date);
            }

            if (!empty($request->end_date)) {
                $query->whereDate('created_at', '<=', $request->end_date);
            }

            $appraisals = $query->get();

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


    public function create()
    {
        if (\Auth::user()->can('Create Appraisal')) {

            $brances = Branch::where('created_by', '=', \Auth::user()->creatorId())->get();

            $employee = Employee::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $employee->prepend('Select Employee', '');
            $performance_types = Performance_Type::where('created_by', '=', \Auth::user()->creatorId())->get();

            return view('appraisal.create', compact('employee', 'brances', 'performance_types'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


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

            // Check if multi-employee mode is enabled
            $isMultiMode = $request->has('multi_employee_mode') && $request->multi_employee_mode;

            // Dynamic validation rules
            $validationRules = [
                'brances' => 'required',
                'rating' => 'required',
            ];

            if ($isMultiMode) {
                $validationRules['employees'] = 'required|array|min:1';
                $validationRules['employees.*'] = 'exists:employees,id'; // Adjust table name as needed
            } else {
                $validationRules['employee'] = 'required';
            }

            $validator = \Validator::make($request->all(), $validationRules);

            if ($validator->fails()) {
                $messages = $validator->getMessageBag();
                return redirect()->back()->with('error', $messages->first());
            }

            try {
                \DB::beginTransaction();

                if ($isMultiMode) {
                    // Handle multiple employees
                    $employeeIds = $request->employees;
                    $createdCount = 0;

                    foreach ($employeeIds as $employeeId) {
                        // Check if appraisal already exists for this employee in the same month/branch
                        $existingAppraisal = Appraisal::where('branch', $request->brances)
                            ->where('employee', $employeeId)
                            ->where('appraisal_date', $request->appraisal_date)
                            ->first();

                        if (!$existingAppraisal) {
                            $appraisal = new Appraisal();
                            $appraisal->branch = $request->brances;
                            $appraisal->employee = $employeeId;
                            $appraisal->appraisal_date = $request->appraisal_date;
                            $appraisal->rating = json_encode($request->rating, true);
                            $appraisal->remark = $request->remark;
                            $appraisal->created_by = \Auth::user()->creatorId();
                            $appraisal->save();

                            $createdCount++;
                        }
                    }

                    \DB::commit();

                    if ($createdCount > 0) {
                        $message = $createdCount === 1
                            ? __('Appraisal successfully created for 1 employee.')
                            : __('Appraisals successfully created for :count employees.', ['count' => $createdCount]);

                        $skippedCount = count($employeeIds) - $createdCount;
                        if ($skippedCount > 0) {
                            $message .= ' ' . __(':count employees were skipped (appraisal already exists).', ['count' => $skippedCount]);
                        }

                        return redirect()->route('appraisal.index')->with('success', $message);
                    } else {
                        return redirect()->route('appraisal.index')->with('warning', __('No new appraisals were created. All selected employees already have appraisals for this period.'));
                    }
                } else {
                    // Handle single employee (original logic)
                    $appraisal = new Appraisal();
                    $appraisal->branch = $request->brances;
                    $appraisal->employee = $request->employee;
                    $appraisal->appraisal_date = $request->appraisal_date;
                    $appraisal->rating = json_encode($request->rating, true);
                    $appraisal->remark = $request->remark;
                    $appraisal->created_by = \Auth::user()->creatorId();
                    $appraisal->save();

                    \DB::commit();
                    return redirect()->route('appraisal.index')->with('success', __('Appraisal successfully created.'));
                }
            } catch (\Exception $e) {
                \DB::rollback();
                return redirect()->back()->with('error', __('An error occurred while creating the appraisal(s). Please try again.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function show(Appraisal $appraisal)
    {
        $rating = json_decode($appraisal->rating, true);
        $all_performance_types = Performance_Type::where('created_by', '=', \Auth::user()->creatorId())->get();
        $employee = Employee::find($appraisal->employee);
        $indicator = Indicator::where('branch', $employee->branch_id)
            ->where('department', $employee->department_id)
            ->where('designation', $employee->designation_id)
            ->first();

        if ($indicator != null) {
            $ratings = json_decode($indicator->rating, true);
        } else {
            $ratings = null;
        }

        // Filter performance types to only include those with ratings
        $performance_types = $all_performance_types->filter(function ($performance_type) use ($rating) {
            // Check if any of the types in this performance_type have ratings
            return $performance_type->types->some(function ($type) use ($rating) {
                return isset($rating[$type->id]) && !empty($rating[$type->id]);
            });
        });

        return view('appraisal.show', compact('appraisal', 'performance_types', 'rating', 'ratings'));
    }


    public function edit(Appraisal $appraisal)
    {
        if (\Auth::user()->can('Edit Appraisal')) {
            $all_performance_types = Performance_Type::where('created_by', '=', \Auth::user()->creatorId())->get();

            $employee   = Employee::where('created_by', \Auth::user()->creatorId())->get()->pluck('name', 'id');
            $employee->prepend('Select Employee', '');

            $brances = Branch::where('created_by', '=', \Auth::user()->creatorId())->get();
            $rating = json_decode($appraisal->rating, true);

            // Filter performance types to only include those with ratings in this appraisal
            $performance_types = $all_performance_types->filter(function ($performance_type) use ($rating) {
                // Check if any of the types in this performance_type have ratings
                return $performance_type->types->some(function ($type) use ($rating) {
                    return isset($rating[$type->id]) && !empty($rating[$type->id]);
                });
            });

            return view('appraisal.edit', compact('brances', 'employee', 'appraisal', 'performance_types', 'rating'));
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }


    public function update(Request $request, Appraisal $appraisal)
    {

        if (\Auth::user()->can('Edit Appraisal')) {
            $validator = \Validator::make(
                $request->all(),
                [
                    'brances' => 'required',
                    'employees' => 'required',
                    'rating' => 'required',
                ]
            );
            if ($validator->fails()) {
                $messages = $validator->getMessageBag();

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

            $appraisal->branch         = $request->brances;
            $appraisal->employee       = $request->employees;
            $appraisal->appraisal_date = $request->appraisal_date;
            $appraisal->rating         = json_encode($request->rating, true);
            $appraisal->remark         = $request->remark;
            $appraisal->save();

            return redirect()->route('appraisal.index')->with('success', __('Appraisal successfully updated.'));
        }
    }

    public function destroy(Appraisal $appraisal)
    {
        if (\Auth::user()->can('Delete Appraisal')) {
            if ($appraisal->created_by == \Auth::user()->creatorId()) {
                $appraisal->delete();

                return redirect()->route('appraisal.index')->with('success', __('Appraisal successfully deleted.'));
            } else {
                return redirect()->back()->with('error', __('Permission denied.'));
            }
        } else {
            return redirect()->back()->with('error', __('Permission denied.'));
        }
    }
    public function empByStar(Request $request)
    {
        $employee = Employee::find($request->employee);
        // $indicator = Indicator::where('branch',$employee->branch_id)->where('department',$employee->department_id)->first();
        $indicator = Indicator::where('branch', $employee->branch_id)->where('department', $employee->department_id)->where('designation', $employee->designation_id)->first();

        if ($indicator != null) {
            $ratings = json_decode($indicator->rating, true);
        } else {
            $ratings = null;
        }

        // $ratings = json_decode($indicator->rating, true);

        $performance_types = Performance_Type::where('created_by', '=', \Auth::user()->creatorId())->get();

        $viewRender = view('appraisal.star', compact('ratings', 'performance_types'))->render();

        return response()->json(array('success' => true, 'html' => $viewRender));
    }

    public function empByStarModified(Request $request)
    {
        $employee = Employee::find($request->employee);

        $indicator = Indicator::where('branch', $employee->branch_id)
            ->where('department', $employee->department_id)
            ->where('designation', $employee->designation_id)
            ->first();

        $ratings = $indicator ? json_decode($indicator->rating, true) : [];

        $performance_types = Performance_Type::with('types')
            ->where('created_by', \Auth::user()->creatorId())
            ->get();

        return response()->json([
            'success' => true,
            'ratings' => $ratings,
            'performance_types' => $performance_types,
        ]);
    }
    public function empByStar1(Request $request)
    {
        $employee = Employee::find($request->employee);

        $appraisal = Appraisal::find($request->appraisal);

        $indicator = Indicator::where('branch', $employee->branch_id)->where('department', $employee->department_id)->where('designation', $employee->designation_id)->first();

        if ($indicator != null) {
            $ratings = json_decode($indicator->rating, true);
        } else {
            $ratings = null;
        }

        // $ratings = json_decode($indicator->rating, true);
        $rating = json_decode($appraisal->rating, true);
        $performance_types = Performance_Type::where('created_by', '=', \Auth::user()->creatorId())->get();
        $viewRender = view('appraisal.staredit', compact('ratings', 'rating', 'performance_types'))->render();
        return response()->json(array('success' => true, 'html' => $viewRender));
    }
    public function getemployee(Request $request)
    {
        $data['employee'] = Employee::where('branch_id', $request->branch_id)->get();

        // $employees = Employee::where('branch_id', $request->branch)->get()->pluck('name', 'id')->toArray();

        return response()->json($data);
    }
    public function getDepartmentByBranch(Request $request)
    {
        $data = Department::where('branch_id', $request->branch_id)->get();
        return response()->json([
            'exists' => true,
            'departments' => $data,
        ]);
    }

    public function getEmployeesByDepartment(Request $request)
    {
        $data = Employee::where('department_id', $request->department_id)->get();
        return response()->json($data);
    }

    public function checkBranchIndicator(Request $request)
    {
        $branchExists = Indicator::where('branch', $request->branch_id)
            ->where('created_by', \Auth::user()->creatorId())
            ->exists();

        return response()->json(['exists' => $branchExists]);
    }
}
