<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\TaxTable;
use App\Models\PayrollSetting;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class TaxTableController extends Controller
{

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $payrollSetting = PayrollSetting::first();
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $period = $request->input('period', $payrollSetting->tax_table_basis);
        $data = TaxTable::where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('period', 'like', '%' . $keyword . '%');
        })
        ->where('period', $period);

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'period' => [
                'required',
                'min:2'
            ]
        ]);

        /** 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 = TaxTable::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()
            ]);
        }
    }

    public function update(Request $request, int $id)
    {
        $data = TaxTable::where('id', $id)->first();

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

        $validator = Validator::make(
            $request->all(),
            [
                'period' => [
                    'required',
                    'min:2'
                ]
            ]
        );

        /** 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()
            ]);
        }
    }

    public function destroy(int $id)
    {
        $data = TaxTable::find($id);
        if (!$data) {
            return response()->json(['message' => "Record not found!"], 204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"], 201);
    }

    public function getShields()
    {
        $data = DB::table('employees as e')
            ->join('mtr_employeelist as mtre', 'e.employee_id', '=', 'mtre.employee_id')
            ->join('hrm_trn_empcompensation as compen', 'mtre.employee_no', '=', 'compen.employee_no')
            ->select('e.employee_id', 'mtre.fixed_pagibig_amount', 'mtre.tax_shield', 'mtre.sss_shield',
                    'mtre.pagibig_shield', 'mtre.philhealth_shield', 'mtre.present_all_times', 'mtre.fixed_pagibig',
                    'mtre.fixed_pagibig_amount_er', 'compen.payment_type')
            ->get();

            foreach ($data as $employee) {
                $shields = json_encode([
                    'tax' => $employee->tax_shield == 'Y' ? '1' : '0',
                    'sss' => $employee->sss_shield == 'Y' ? '1' : '0',
                    'pagibig' => $employee->pagibig_shield == 'Y' ? '1' : '0',
                    'philhealth' => $employee->philhealth_shield == 'Y' ? '1' : '0',
                ]);

                DB::table('salary_and_wages')
                    ->where('employee_id', $employee->employee_id)
                    ->update(['shields' => $shields]);
            }

    }
}
