<?php

namespace App\Http\Controllers\API\v1;
use App\Http\Controllers\Controller;

use App\Models\PayrollItems;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Throwable;

class PayrollItemsController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $addLess = $request->input('add_less', null);
        $tag = $request->input('tag', null);
        
        $data = PayrollItems::where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('name', 'like', '%' . $keyword . '%')
                ->orWhere('description', 'like', '%' . $keyword . '%');
        });
        
        // Apply add_less filter if provided
        if ($addLess !== null) {
            $data = $data->where('add_less', $addLess);
        }
        
        // Apply tag filter if provided
        if ($tag !== null) {
            $data = $data->where('tag', $tag);
        }
        
        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }
        
        $data = $data->paginate($perPage);
        
        return response()->json($data);
    }

    public function store(Request $request)
    {

        $taxable = ($request->taxable && $request->taxable !== 'null' && $request->taxable !== 'false' && trim($request->taxable) !== '' ? 1 : 0);
        $thirteenth_month = ($request->thirteenth_month && $request->thirteenth_month !== 'null' && $request->thirteenth_month !== 'false' && trim($request->thirteenth_month) !== '' ? 1 : 0);

        $request['taxable'] = $taxable;
        $request['thirteenth_month'] = $thirteenth_month;
        
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'min:2',
                Rule::unique('payroll_items')->whereNull('deleted_at')
            ]
        ]);

        /** 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 = PayrollItems::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 = PayrollItems::where('id', $id)->first();

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

        $taxable = ($request->taxable && $request->taxable !== 'null' && $request->taxable !== 'false' && trim($request->taxable) !== '' ? 1 : 0);
        $thirteenth_month = ($request->thirteenth_month && $request->thirteenth_month !== 'null' && $request->thirteenth_month !== 'false' && trim($request->thirteenth_month) !== '' ? 1 : 0);

        $request['taxable'] = $taxable;
        $request['thirteenth_month'] = $thirteenth_month;
        
        $validator = Validator::make($request->all(),
            [
                'name' => [
                    'required',
                    'min:2',
                    Rule::unique('payroll_items')->ignore($id)->whereNull('deleted_at')
                ]
            ]
        );

        /** 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 = PayrollItems::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);
    }
}
