<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\ScheduleShift;
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;

class ScheduleShiftController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    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', '');
        $data = ScheduleShift::where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('name', 'like', '%' . $keyword . '%');
        });

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }
        
        $data = $data->whereNull('schedule_header')->paginate($perPage);
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // dd($request->all());
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'min:2',
                Rule::unique('schedule_shifts')->whereNull('deleted_at')
            ],
            'day_off' => 'required|array|min:1', // Ensure day_off is an array and has at least one day
            'day_off.*' => 'in:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday' // Ensure days are valid
        ]);

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

        // Convert day_off array to comma-separated string
        $dayOffString = implode(',', $request->day_off);
        $request->merge(['day_off' => $dayOffString]);

        $shiftingOffString = implode(',', $request->shifting_day);
        $request->merge(['shifting_day' => $shiftingOffString]);

        $wfhString = implode(',', $request->wfh);
        $request->merge(['wfh' => $wfhString]);

        // Uncomment for debugging if needed
        // dd($request->all());

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

        try {
            // Create the record in the database
            $data = ScheduleShift::create($request->all());

            if($request->every_sat_off){
                $sub_schedule = [
                    'schedule_header' => $data->id, 
                    'name' => $request->name. ' (Sub)',
                    'description' => $request->description,
                    'from_time' => $request->from_time,
                    'to_time' => $request->to_time,
                    'day_off' => 'Sunday'
                ];

                $data = ScheduleShift::create($sub_schedule);
  
                // dd($data);
            }

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

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

        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'min:2',
                Rule::unique('schedule_shifts')->ignore($id)->whereNull('deleted_at')
            ],
            'day_off' => 'required|array|min:1', // Ensure day_off is an array and has at least one day
            'day_off.*' => 'in:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', // Ensure days are valid
        ]);

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

        // Convert day_off array to comma-separated string
        $dayOffString = implode(',', $request->day_off);
        $request->merge(['day_off' => $dayOffString]);

        $shiftingOffString = implode(',', $request->shifting_day);
        $request->merge(['shifting_day' => $shiftingOffString]);

        $wfhString = implode(',', $request->wfh);
        $request->merge(['wfh' => $wfhString]);

        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 = ScheduleShift::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);
    }
}
