<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\RoleCompanyAccess;
use App\Models\RolePermission;
use App\Models\SalaryAndWages;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Throwable;

class SalaryAndWagesController extends Controller
{
    public function index(Request $request, $id)
    {

    }

    public function show(string $id)
    {
        $user = Auth::user();

        $rolesWithSystemId3 = $user->roles->filter(function($role) {
            return $role->group && $role->group->system_id === 3;
        });

        // Get dealers for ALL roles with system_id 3
        $dealers = [];
        $roleIds = [];
        if ($rolesWithSystemId3->isNotEmpty()) {
            $roleIds = $rolesWithSystemId3->pluck('id')->toArray();
            
            $dealers = RoleCompanyAccess::whereIn('role_id', $roleIds)
                ->pluck('dealership_id')
                ->unique()
                ->toArray();
        }

        DB::enableQueryLog();

        $hasPermission = RolePermission::whereIn('dealership_id', $dealers)
            ->whereIn('role_id', $roleIds)
            ->where('module_id', 262)
            ->where('permission_id', 1)
            ->exists();

        try {
            $id = Crypt::decrypt($id);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $id = $id;
        }

        // dd($id);
        $data = Employee::with([
            'position',
            'salary_and_wages'
        ])
        ->select(DB::raw("CONCAT(firstname, ' ', lastname) as full_name"), 'employees.*')
        ->where('employees.employee_id', '=', $id)->first();
        
        if(!$hasPermission){
            $data['salary_and_wages']->salary_rate = '******';
        }
        
        return response()->json($data);
    }

    public function store(Request $request, string $employee_id)
    {
        try {
            $employee_id = Crypt::decrypt($employee_id);
            $request['employee_id'] = Crypt::decrypt($request->employee_id);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            $employee_id = $employee_id;
        }

        $shieldsData = [
            "tax" => $request->tax ? 1 : 0,
            "no_tax" => $request->tax ? 1 : 0,
            "sss" => $request->sss ? 1 : 0,
            "no_sss" => $request->sss ? 1 : 0,
            "pagibig" => $request->pagibig ? 1 : 0,
            "no_pagibig" => $request->pagibig ? 1 : 0,
            "philhealth" => $request->philhealth ? 1 : 0,
            "no_philhealth" => $request->philhealth ? 1 : 0,
            "no_late" => $request->no_late ? 1 : 0,
            "no_undertime" => $request->no_undertime ? 1 : 0,
            "no_overtime" => $request->no_overtime ? 1 : 0
        ];

        $request['shields'] = json_encode($shieldsData);

        $employeeExists = SalaryAndWages::where('employee_id', $employee_id)->exists();
        
        $validator = Validator::make($request->all(), [
            'salary_rate' => [
                'required',
                'min:1',
            ],
        ]);

        if($employeeExists){
            $data = SalaryAndWages::where('employee_id', $employee_id)->first();

            if (!$data) {
                return response()->json(['messages' => 'No data found.'], 404);
            }

            /** If validation fails return with error message */
            if ($validator->fails()) {
                $errors = $validator->errors();
                $first = $errors->getMessages();
                return response()->json([
                    'status'  => false,
                    'message' => (reset($first))[0],
                    'errors'  => $errors
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            DB::connection()->beginTransaction();

            try {

                $data->fill($request->all());
                $data->save();

                $data->touch();

                DB::connection()->commit();

                return response()->json([
                    'message' => 'Record Successfully updated!',
                    'status' => 'success',
                    'data' => $data,
                ], 201);

            } catch (Throwable $e) {
                DB::connection()->rollback();
                return response()->json([
                    'status'  => false,
                    'message' => 'Unable to process request. Please try again.',
                    'data'    => $e->getMessage()
                ]);
            }
        } else {
            /** If validation fails return with error message */
            if ($validator->fails()) {
                $errors = $validator->errors();
                $first = $errors->getMessages();
                return response()->json([
                    'status'  => false,
                    'message' => (reset($first))[0],
                    'errors'  => $errors
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            DB::connection()->beginTransaction();

            try {

                $data = SalaryAndWages::create($request->all());

                DB::connection()->commit();

                return response()->json([
                    'message' => 'Record Successfully added!',
                    'status' => 'success',
                ],201);

            } catch (Throwable $e) {
                DB::connection()->rollback();
                return response()->json([
                    'status'  => false,
                    'message' => 'Unable to process request. Please try again.',
                    'data'    => $e->getMessage()
                ]);
            }
        }
    }
}
