<?php
namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\AttendancePosting;
use App\Models\AttendancePostingDtls;
use App\Models\ProcessedTimelog;
use App\Models\ProcessedAbsent;
use App\Models\ProcessedLeave;
use App\Models\ProcessedOb;
use App\Models\ProcessedTardiness;
use App\Models\ProcessedUndertime;
use App\Models\ProcessedOvertime;
use App\Models\ProcessedNightDifferential;
use App\Models\ProcessedHolidayRestdayDuty;
use App\Models\ProcessedDailyWorkHours;
use App\Models\ProcessedSchedule;
use App\Models\Timelog;
use App\Models\EmployeeChangeSchedule;
use App\Models\EmployeeLeave;
use App\Models\EmployeeOb;
use App\Models\EmployeeOvertime;
use App\Models\EmployeeTimeAdjustment;
use App\Models\TimelogEdit;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Carbon\Carbon;
use App\Helpers\CommonHelper;
use App\Models\EmployeeOffset;
use App\Models\ProcessedOffsetAvailment;
use Illuminate\Support\Facades\Auth;
use DateInterval;
use DatePeriod;
use DateTime;

class AttendancePostingController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', null);
        if($keyword) $keyword = str_replace(' ','%', $keyword);
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', null);
        $sortType = $request->input('sortType', null);
        $data = AttendancePosting::with(['company','dealership'])->whereIn('dealership_id', $request->dealers)
        ->when($keyword, fn($q) => $q->whereHas('company', fn($qc) => $qc->where('name', 'like', '%'.$keyword.'%'))->orWhereHas('dealership', fn($qc) => $qc->where('name', 'like', '%'.$keyword.'%'))->orWhere('payroll_date', 'like', $keyword.'%'))
        ->when($sortBy, fn ($q) => $q->orderBy($sortBy, $sortType))
        ->orderBy('created_at', 'desc')
        ->paginate($perPage);

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


    /**
     * Store a newly created resource in storage.
     */
    // app/Http/Controllers/API/v1/AttendancePostingController.php

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'payroll_date' => 'required|date_format:Y-m-d',
            'company_id' => 'required',
            'dealership_id' => '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 = AttendancePosting::where([
                'payroll_date' => $request->payroll_date,
                'company_id' => $request->company_id,
                'dealership_id' => $request->dealership_id
            ])->first();

            if($data) {
                $data->touch();
                $reference_no = $data->reference_no;
            } else {
                $prefix = join('-', [
                    'ATP',
                    \App\Models\Dealership::find($request->dealership_id)->code
                ]);
                
                /**get reference code */
                do {
                    $reference_no = CommonHelper::generateReferenceCode($prefix);
                } while (AttendancePosting::where('reference_no', $reference_no)->exists());

                $data = AttendancePosting::create(array_merge(
                    $request->except(['details']),
                    [
                        'reference_no' => $reference_no
                    ]
                ));
            }
            
            AttendancePostingDtls::where(['header_id' => $data->id])->delete();
            
            foreach($request->details as $detail) {
                // Sanitize numeric fields
                $cleanDetail = array_merge($detail, [
                    'work_days' => $this->sanitizeNumeric($detail['work_days'] ?? null),
                    'actual_work_days' => $this->sanitizeNumeric($detail['actual_work_days'] ?? null),
                    'work_hours' => $this->sanitizeNumeric($detail['work_hours'] ?? null),
                    'leave_hours' => $this->sanitizeNumeric($detail['leave_hours'] ?? null),
                    'days_absent' => $this->sanitizeNumeric($detail['days_absent'] ?? null),
                    'hours_absent' => $this->sanitizeNumeric($detail['hours_absent'] ?? null),
                    'minutes_late' => $this->sanitizeNumeric($detail['minutes_late'] ?? null),
                    'minutes_undertime' => $this->sanitizeNumeric($detail['minutes_undertime'] ?? null),
                ]);

                $dtls = AttendancePostingDtls::create(array_merge(
                    $cleanDetail,
                    [
                        'header_id' => $data->id,
                        'reference_no' => $data->reference_no,
                    ]
                ));

                /** Update processed details */
                $where = ['payroll_date' => $request->payroll_date, 'employee_id' => $detail['employee_id']];
                $updateData = ['header_id' => $data->id];
                ProcessedTimelog::where($where)->update($updateData);
                ProcessedAbsent::where($where)->update($updateData);
                ProcessedTardiness::where($where)->update($updateData);
                ProcessedUndertime::where($where)->update($updateData);
                ProcessedOvertime::where($where)->update($updateData);
                ProcessedLeave::where($where)->update($updateData);
                ProcessedHolidayRestdayDuty::where($where)->update($updateData);
                ProcessedDailyWorkHours::where($where)->update($updateData);
                ProcessedSchedule::where($where)->update($updateData);
                ProcessedOb::where($where)->update($updateData);
                ProcessedOffsetAvailment::where($where)->update($updateData);
            }

            DB::connection()->commit();
            return response()->json([
                'message' => 'Record Successfully added!',
                '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);
        }
    }

    /**
     * Sanitize numeric values - convert NaN and invalid values to 0
     * 
     * @param mixed $value
     * @return float
     */
    private function sanitizeNumeric($value)
    {
        // Return 0 if null or empty
        if ($value === null || $value === '' || $value === 'NaN') {
            return 0;
        }

        // If it's already a numeric value
        if (is_numeric($value)) {
            return (float) $value;
        }

        // If it's a string, try to convert
        if (is_string($value)) {
            // Remove whitespace
            $value = trim($value);
            
            // Check for NaN string
            if (strtoupper($value) === 'NAN') {
                return 0;
            }
            
            // Try to convert
            if (is_numeric($value)) {
                return (float) $value;
            }
        }

        // Default to 0 if can't convert
        return 0;
    }


    /**
     * Display the specified resource.
     */
    public function show(Request $request, string $payroll_date)
    {
        $company_id = $request->company_id;
        $data = AttendancePostingDtls::select('dealership_id', 'department_id')
        ->whereHas('header', fn($q) => $q->where(['payroll_date' => $payroll_date, 'company_id' => $company_id]))
        ->distinct()
        ->orderBy('dealership_id')
        ->orderBy('department_id')
        ->get() // Fetch all records
        ->map(function ($item) use($payroll_date, $company_id) {
            $posted = AttendancePosting::where(['payroll_date' => $payroll_date, 'company_id' => $company_id,'dealership_id'=>$item['dealership_id']])->whereNotNull('posted_at')->first();
            $item->posted = $posted ? true : false;
            return $item;
        });
        // dd(DB::getQueryLog());

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



    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $id)
    {
        $data = AttendancePosting::where('id', $id)->first();

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

        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'payroll_date' => 'required|date_format:Y-m-d',
        ]);

        /** 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->fill($request->all());
            $data->save();

            $data->touch();

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

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

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $id)
    {
        $data = AttendancePosting::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        try {

            $data->delete();
            DB::connection()->commit();
            return response()->json(['message' => "Record successfully deleted!"],201);

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

    public function getProcessedRecords(Request $request)
    {
        $where = $request->toArray();
        $header = AttendancePosting::with(['dealership'])->where($where)->first();

        DB::enableQueryLog();
        $details = AttendancePostingDtls::with(['employee', 'department', 'employee.position'])->where([
            'attendance_posting_details.company_id' => $request->company_id,
            'attendance_posting_details.dealership_id' => $request->dealership_id,
        ])
        ->wherehas('header', fn($q) => $q->where($where))
        ->join('employees', 'attendance_posting_details.employee_id', '=', 'employees.employee_id')
        ->orderBy('employees.lastname')
        ->orderBy('employees.firstname')
        ->orderBy('employees.middlename')
        ->select('attendance_posting_details.*') // Important to avoid column conflicts
        ->whereNull('employees.deleted_at')
        ->whereNull('employees.date_resign')
        ->get();

        // dd(DB::getQueryLog());
        $timelogs = ProcessedTimelog::where($where)->orderBy('department_id')->get();
        $absences = ProcessedAbsent::where($where)->orderBy('department_id')->get();
        $tardiness= ProcessedTardiness::where($where)->orderBy('department_id')->get();
        $undertimes = ProcessedUndertime::where($where)->orderBy('department_id')->get();
        $overtimes = ProcessedOvertime::where($where)->orderBy('department_id')->get();
        $night_differentials = ProcessedNightDifferential::where($where)->orderBy('department_id')->get();
        $leaves = ProcessedLeave::where($where)->orderBy('department_id')->get();
        $obs = ProcessedOb::where($where)->orderBy('department_id')->get();
        $offsets = ProcessedOffsetAvailment::where($where)->orderBy('department_id')->get();
        $holidayRestdays = ProcessedHolidayRestdayDuty::where($where)->orderBy('department_id')->get();
        $dailyWorkHours = ProcessedDailyWorkHours::where($where)->orderBy('department_id')->get();
        $schedules = ProcessedSchedule::where($where)->orderBy('department_id')->get();

        return response()->json(['header'=>$header, 'details' => $details, 'attendance' => [
            'timelog' => $timelogs,
            'absent' => $absences,
            'tardiness' => $tardiness,
            'undertime' => $undertimes,
            'overtime' => $overtimes,
            'night_differential' => $night_differentials,
            'leave' => $leaves,
            'ob' => $obs,
            'offset' => $offsets,
            'holiday' => $holidayRestdays,
            'schedule' => $schedules,
            'dailyWorkHours' => $dailyWorkHours,
        ]]);

    }

    public function updateTimelog(Request $request)
    {
        DB::beginTransaction();
        try {
            $where =  [
                'payroll_date' =>$request->payroll_date,
                'company_id' =>$request->company_id,
                'dealership_id' =>$request->dealership_id,
                'employee_id' => $request->employee_id,
                'date' => $request->date,
            ];
            $whereDetail = [
                'company_id' =>$request->company_id,
                'dealership_id' =>$request->dealership_id,
                'employee_id' => $request->employee_id,
            ];
            $updateData =[
                'payroll_date' =>$request->payroll_date,
                'company_id' =>$request->company_id,
                'dealership_id' =>$request->dealership_id,
                'department_id' =>$request->department_id,
                'employee_id' => $request->employee_id,
                'date' => $request->date,
                'time' => $request->time,
                'in_out' => $request->in_out,
                'reason' => $request->reason,
                'created_by' => Auth::user()->employee_id,
            ];

            // TimelogEdit::updateOrCreate($where, $updateData);
            TimelogEdit::create($updateData);

                DB::commit();

        //     $timelog = ProcessedTimelog::where($where)->where('in_out', $request->in_out)->first();
        //     // DB::enableQueryLog();
        //     if(!is_null($timelog)) {
        //         ProcessedTimelog::where($where)->where('in_out', $request->in_out)->update($updateData);
        //     } else {
        //         ProcessedTimelog::create($updateData);
        //     }
        //     // dd(DB::getQueryLog());
        //     // dd($timelog);
        //     /**Fetch existing processed records */
        //     $timelogs = ProcessedTimelog::where($where)->get();
        //     $schedule = ProcessedSchedule::where($where)->first();
        //     $tardiness= ProcessedTardiness::where($where)->first();
        //     $undertime = ProcessedUndertime::where($where)->first();
        //     $detail = AttendancePostingDtls::where($whereDetail)->first();

        //     /**Update tardiness */
        //     if($request->in_out = 'I' && $timelogs && !is_null($timelogs->first(fn($tl) => $tl->in_out == 'I'))) {
        //         $timelog = $timelogs->first(fn($tl) => $tl->in_out == 'I');
        //         $timeIn = Carbon::parse($timelog['date'].' '.$timelog['time']);
        //         $schedIn = Carbon::parse($schedule->date. ' '.$schedule->sched_in);
        //         $interval = $timeIn->diff($schedIn);
        //         $schedIn->add(new DateInterval('PT6M')); // Add 5 minutes grace period
        //         $minutes_tardy = 0;
        //         if ($timeIn > $schedIn) {
        //             // Calculate the difference
        //             // return $interval->format('%I minutes');
        //             $minutes = (int) ltrim($interval->format('%i'), '0');
        //             $minutes_tardy = floor($minutes);
        //         }

        //         $minutes_differ = 0;

        //         $minutes_differ = $minutes_tardy - ($tardiness ? $tardiness->no_of_minutes : 0);
        //         // dd($minutes_tardy);
        //         if($minutes_tardy ==0 && $tardiness) {
        //             ProcessedTardiness::where($where)->delete();
        //         } elseif ($minutes_tardy > 0) {
        //             ProcessedTardiness::updateOrCreate($where,
        //                 array_merge($where,[
        //                     'no_of_minutes' => $minutes_tardy,
        //                 ]));
        //         }
        //         $updated_minutes = ($detail ? $detail->minutes_late : 0) + $minutes_differ;
        //         AttendancePostingDtls::where($whereDetail)->update(['minutes_undertime' => $updated_minutes]);
        //     }


        //     /**if request is out, update undertime*/
        //     if($request->in_out = 'O' && $timelogs && !is_null($timelogs->first(fn($tl) => $tl->in_out == 'O'))) {
        //         $timelog = $timelogs->first(fn($tl) => $tl->in_out == 'O');
        //         $timeOut = Carbon::parse($timelog->date.' '.$timelog->time);
        //         $schedOut = Carbon::parse($schedule->date. ' '.$schedule->sched_out);
        //         $interval = $schedOut->diff($timeOut);
        //         $minutes_undertime = 0;
        //         if ($schedOut > $timeOut) {
        //             // Calculate the difference
        //             // return $interval->format('%I minutes');
        //             $minutes = (int) ltrim($interval->format('%i'), '0');
        //             $minutes_undertime = floor($minutes);
        //         }

        //         $minutes_differ = 0;

        //         $minutes_differ = $minutes_undertime - ($undertime ? $undertime->no_of_minutes : 0);
        //         if($minutes_undertime ==0 && $undertime) {
        //             ProcessedUndertime::where($where)->delete();
        //         } elseif ($minutes_undertime > 0) {
        //             if(!is_null($undertime)) {

        //                 ProcessedUndertime::where($where)->update([
        //                         'no_of_minutes' => $minutes_undertime
        //                     ]);
        //             } else {
        //                 $time_in = !is_null($timelogs->first(fn($tl) => $tl->in_out=='I')) ? $timelogs->first(fn($tl) => $tl->in_out=='I')->time : null;
        //                 $time_out = !is_null($timelogs->first(fn($tl) => $tl->in_out=='O')) ? $timelogs->first(fn($tl) => $tl->in_out=='O')->time : null;
        //                 ProcessedUndertime::create([
        //                     'payroll_date' =>$request->payroll_date,
        //                     'company_id' =>$request->company_id,
        //                     'dealership_id' =>$request->dealership_id,
        //                     'department_id' =>$request->department_id,
        //                     'employee_id' => $request->employee_id,
        //                     'date' => $request->date,
        //                     'no_of_minutes' => $minutes_undertime,
        //                     'schedule_in' => $schedule->schedule_in,
        //                     'schedule_out' => $schedule->schedule_out,
        //                     'time_in' => $time_in,
        //                     'time_out' => $time_out,
        //                 ]);
        //             }
        //         }
        //         $updated_minutes = ($detail ? $detail->minutes_undertime : 0) + $minutes_differ;
        //         AttendancePostingDtls::where($whereDetail)->update(['minutes_undertime' => $updated_minutes]);
        //     }

        //     DB::commit();

        //     unset($where['date']);
        //     /**Fetch updated records before response */
        //     $timelogs = ProcessedTimelog::where($where)->get();
        // $absences = ProcessedAbsent::where($where)->get();
        // $tardiness= ProcessedTardiness::where($where)->get();
        // $undertimes = ProcessedUndertime::where($where)->get();
        // $overtimes = ProcessedOvertime::where($where)->get();
        // $leaves = ProcessedLeave::where($where)->get();
        // $holidayRestdays = ProcessedHolidayRestdayDuty::where($where)->get();
        // $dailyWorkHours = ProcessedDailyWorkHours::where($where)->get();
        // $schedules = ProcessedSchedule::where($where)->get();
        // $details = AttendancePostingDtls::where($whereDetail)->first();
        // $data = [
        //     'timelog' => $timelogs,
        //     'absent' => $absences,
        //     'tardiness' => $tardiness,
        //     'undertime' => $undertimes,
        //     'overtime' => $overtimes,
        //     'leave' => $leaves,
        //     'holiday' => $holidayRestdays,
        //     'schedule' => $schedules,
        //     'dailyWorkHours' => $dailyWorkHours,
        // ];
            return response()->json([
                'message' => 'Record Successfully added!',
                'status' => 'success',
                // 'data' => $data,
                // 'details' => $details,
            ],201);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function updateAttendanceByEmployee(Request $request) {
        $payroll_date = $request->input('payroll_date');
        $company_id = $request->input('company_id');
        $dealership_id = $request->input('dealership_id');
        $employee_id = $request->input('employee_id');
        $date_from = $request->input('date_from', null);
        $date_to = $request->input('date_to', null);
        $date = $request->input('date', null);
        /**GEt timelogs */
        $where = [
            'payroll_date' => $payroll_date,
            'company_id' => $company_id,
            'dealership_id' => $dealership_id,
            'employee_id' => $employee_id,
            'date' => $date,
        ];
        $timelogs = ProcessedTimelog::where($where)->get();
        $schedules = ProcessedSchedule::where($where)->first();
        $tardiness= ProcessedTardiness::where($where)->first();
        $undertimes = ProcessedUndertime::where($where)->first();
        $overtimes = ProcessedOvertime::where($where)->first();
        $leaves = ProcessedLeave::where($where)->first();
        $holidayRestdays = ProcessedHolidayRestdayDuty::where($where)->first();
        $absences = ProcessedAbsent::where($where)->first();
        $dailyWorkHours = ProcessedDailyWorkHours::where($where)->first();

        /**compute tardiness */
        if($timelogs && $timelogs->filter(fn($tl) => $tl->in_out =='I')->isNotEmpty()) {
            $time_in = $timelogs->filter(fn($tl) => $tl->in_out=='I')->toArray();
            $firstTimelogTime = Carbon::parse($time_in['date'].' '.$time_in['time']);
            $scheduledStartTime = Carbon::parse($schedules->data. ' '.$schedules->sched_in);
            $interval = $firstTimelogTime->diff($scheduledStartTime);
        }

        $scheduledStartTime->add(new DateInterval('PT6M')); // Add 5 minutes grace period

        $minutes_tardy = 0;
        if ($firstTimelogTime > $scheduledStartTime) {
            // Calculate the difference
            // return $interval->format('%I minutes');
            $minutes = (int) ltrim($interval->format('%i'), '0');
            $minutes_tardy = floor($minutes);
        }

        if($minutes_tardy ==0 && $tardiness) {
            ProcessedTardiness::where($where)->delete();
        } elseif ($minutes_tardy > 0) {
            ProcessedTardiness::updateOrCreate($where,
                array_merge($where,[
                    'no_of_minutes' => $minutes_tardy,
                    ''
                ]));
        }
    }

    /**
     * Post specified resource in storage.
     */
    public function postRecord(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'payroll_date' => 'required|date_format:Y-m-d',
        ]);

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


        $payroll_date = $request->input('payroll_date');
        $company_id = $request->input('company_id');
        $dealership_id = $request->input('dealership_id');

        $data = AttendancePosting::where(['payroll_date' => $payroll_date, 'company_id' => $company_id, 'dealership_id' => $dealership_id])->first();

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

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

        try {

            $data->fill(['posted_at' => $this->current_datetime, 'posted_by'=>auth()->user()->employee_id]);
            $data->save();

            $data->touch();

             /**Update the requests as posted */
             EmployeeLeave::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date_to','>=',$data->start_date)
             ->where('date_to', '<=', $data->end_date)
             ->whereNull('posting_id')
             ->update(['posted' => 1, 'posting_id'=>$data->id]);
             EmployeeOvertime::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date_to','>=',$data->start_date)
             ->where('date_to', '<=', $data->end_date)
             ->whereNull('posting_id')
             ->update(['posted' => 1, 'posting_id'=>$data->id]);
             EmployeeOb::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date_to','>=',$data->start_date)
             ->where('date_to', '<=', $data->end_date)
             ->whereNull('posting_id')
             ->update(['posted' => 1, 'posting_id'=>$data->id]);
             EmployeeOffset::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date_to','>=',$data->start_date)
             ->where('date_to', '<=', $data->end_date)
             ->whereNull('posting_id')
             ->update(['posted' => 1, 'posting_id'=>$data->id]);
             EmployeeTimeAdjustment::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date','>=',$data->start_date)
             ->where('date', '<=', $data->end_date)
             ->whereNull('posting_id')
             ->update(['posted' => 1, 'posting_id'=>$data->id]);
             EmployeeChangeSchedule::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date','>=',$data->start_date)
             ->where('date', '<=', $data->end_date)
             ->whereNull('posting_id')
             ->update(['posted' => 1, 'posting_id'=>$data->id]);
            //  EmployeeOffset::where(['company_id' => $data->company_id, 'dealer_id' => $data->dealership_id, 'processed' => 1])->where('date_to','>=',$data->start_date)->where('date_to', '<=', $data->end_date)->whereNull('posting_id')->update(['posted' => 1, 'posting_id'=>$data->id]);

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

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

        } catch (\Exception $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }
    /**
     * Post specified resource in storage.
     */
    public function unpostRecord(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'payroll_date' => 'required|date_format:Y-m-d',
        ]);

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


        $payroll_date = $request->input('payroll_date');
        $company_id = $request->input('company_id');
        $dealership_id = $request->input('dealership_id');

        $data = AttendancePosting::where(['payroll_date' => $payroll_date, 'company_id' => $company_id, 'dealership_id' => $dealership_id])->first();

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



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

        try {

            $data->fill(['posted_at' => null, 'posted_by'=>auth()->user()->employee_id]);
            $data->save();

            $data->touch();

             /**Update the requests as posted */
             EmployeeLeave::where('posting_id', $data->id)->update(['posted' => 0, 'posting_id'=>null]);
             EmployeeOvertime::where('posting_id', $data->id)->update(['posted' => 0, 'posting_id'=>null]);
             EmployeeOb::where('posting_id', $data->id)->update(['posted' => 0, 'posting_id'=>null]);
             EmployeeOffset::where('posting_id', $data->id)->update(['posted' => 0, 'posting_id'=>null]);
             EmployeeTimeAdjustment::where('posting_id', $data->id)->update(['posted' => 0, 'posting_id'=>null]);
             EmployeeChangeSchedule::where('posting_id', $data->id)->update(['posted' => 0, 'posting_id'=>null]);

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

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

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

    public function getTimelogRecords(Request $request)
    {
        $employee_id = $request->employee_id;
        $time_keeping_id = $request->time_keeping_id;
        $date = $request->date;
        $in_out = $request->in_out;
        try {
            $timelogs = Timelog::where('time_keeping_id', $time_keeping_id)
            ->whereDate('datetimelog',$date)
            ->get();
            $time_adjustments = EmployeeTimeAdjustment::where(['employee_id' => $employee_id, 'date'=>$date, 'in_out' => $in_out])
            ->first();
            $timelog_edit = TimelogEdit::where(['employee_id' => $employee_id, 'date'=>$date, 'in_out' => $in_out])
            ->first();

            return response()->json([
                'timelogs' => $timelogs,
                'time_adjustments' => $time_adjustments,
                'timelog_edit' => $timelog_edit,
            ], 200);

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