<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
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 PayrollSettingController extends Controller
{

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $data = PayrollSetting::first();

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

    public function show(int $id)
    {
        $data = PayrollSetting::where('id', '=',$id)->first();

        return response()->json($data);
    }
    public function companySetting(Request $request)
    {
        // $data = PayrollSetting::where('id', '=',$id)->first();
        $company_id = $request->input('company_id',null);
        $data = PayrollSetting::where('company_id', $company_id)->first();
        // var_dump($data);exit;
        if(!$data) {
            $data = PayrollSetting::whereNull('company_id')->first();
        }
        // $data = PayrollSetting::when($company_id, fn($q) => $q->where('company_id', '=',$company_id))
        // ->when(!$company_id, fn($q) => $q->whereNull($company_id))
        // ->first();
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'night_differential_rate' => 'required',
            'pagibig_settings_frequency' => 'required',
            // 'pagibig_settings_basis' => 'required',
            'sss_settings_frequency' => 'required',
            // 'sss_settings_basis' => 'required',
            'philhealth_settings_frequency' => 'required',
            // 'philhealth_settings_basis' => 'required',
            'withholding_tax_settings_frequency' => 'required',
            // 'withholding_tax_settings_basis' => 'required',
            'tax_table_basis' => 'required',
            'working_days_per_year' => 'required',
            'payment_type' => 'required',
            // 'cola_range_from' => 'required',
            // 'cola_range_to' => 'required',
            'minimum_wage_for_tax_exemption' => 'required',
            'night_differential_from' => 'required',
            'night_differential_to' => 'required',
            'overtime_minute_from' => 'required',
            'overtime_minute_to' => 'required',
            'late_grace_period' => 'required',
            'undertime_grace_period' => 'required',
            'undertime_minute_from' => 'required',
            'undertime_minute_to' => 'required',
            // 'max_undertime_minute' => 'required',
            // 'gross_income_formula' => 'required',
        ]);

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

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

        try {

            $data = PayrollSetting::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 $company_id)
    {

        $validator = Validator::make($request->all(),
        [
                'night_differential_rate' => 'required',
                'pagibig_settings_frequency' => 'required',
                // 'pagibig_settings_basis' => 'required',
                'sss_settings_frequency' => 'required',
                // 'sss_settings_basis' => 'required',
                'philhealth_settings_frequency' => 'required',
                // 'philhealth_settings_basis' => 'required',
                'withholding_tax_settings_frequency' => 'required',
                // 'withholding_tax_settings_basis' => 'required',
                'tax_table_basis' => 'required',
                'working_days_per_year' => 'required',
                'payment_type' => 'required',
                // 'cola_range_from' => 'required',
                // 'cola_range_to' => 'required',
                'minimum_wage_for_tax_exemption' => 'required',
                'night_differential_from' => 'required',
                'night_differential_to' => 'required',
                'overtime_minute_from' => 'required',
                'overtime_minute_to' => 'required',
                'late_grace_period' => 'required',
                'late_grace_period_manager' => 'required',
                'undertime_minute_from' => 'required',
                'undertime_minute_to' => 'required',
                // 'max_undertime_minute' => 'required',
                // 'gross_income_formula' => 'required',
                ]
            );

            /** 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 = PayrollSetting::where('company_id', $company_id)->first();
                if(!$data) {
                    $data = PayrollSetting::whereNull('company_id')->first();
                }
                if($data) {

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

                    $data->touch();
                } else {
                    PayrollSetting::create($request->all());
                }

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

            return response()->json([
                'message' => 'Record Successfully saved!',
                '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()
            ], 422);
        }
    }

    public function destroy(int $id)
    {
        $data = PayrollSetting::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);
    }
}
