<?php

namespace App\Http\Controllers\Backend\Hr\Attend;

use App\Http\Controllers\Controller;
use App\Models\Hr\Attend\ManualAtt;
use App\Models\User;
// use App\Models\Employee;
use Carbon\Carbon;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class ManualAttController extends Controller
{
    public function index() {
        // if (Auth::id() == 1) {
        //     $organizations = ManualAtt::orderBy('id', 'desc')->get();
        // } else {
        //     $organizations = User::findOrfail(Auth::id())->organizations;
        // }

        $session_data = DB::table('organization_session as ac')->where('ac.session_status', 1)->get();
        $leave_type_data = DB::table('hr_leave_type as ac')->where('ac.status', '=', 'Active')->get();

        $employees = DB::table('employees as emp')->leftJoin('employees_records as erd', 'erd.employee_id', '=', 'emp.id')
        ->leftJoin('designations as dsg', 'dsg.id', '=', 'emp.designation_id')
        ->select('emp.*', 'dsg.name AS designation_name', 'erd.rec_id')->where('emp.status', 1)->whereIn('erd.rec_type', [1])
        ->orderBy('emp.employee_no', 'ASC')->get();

        $leaves = DB::table('emp_leave_apps as ac')->leftJoin('emp_leave_apps_details as acd', 'acd.ela_id', '=', 'ac.ela_id')
        ->leftJoin('organization_session as oss', 'oss.session_id', '=', 'ac.session_id')
        ->select('ac.*', 'oss.*', DB::raw("group_concat(DATE_FORMAT(acd.leavedate, '%d/%m/%Y') SEPARATOR ', ') as leavedatess"))
        ->groupBy('acd.ela_id')->get();
            // ->where('acd.leavedate','LIKE',"$year-%")->where('ac.lStatus', 2)
        // return $employees; exit;
        return view('backend.hr.attend.leave', compact('leaves', 'employees', 'leave_type_data', 'session_data'));
    }
    public function leaveType() {
        $leaveTypes = DB::table('hr_leave_type')->get();
        return view('backend.hr.attend.leaveType', compact('leaveTypes'));
    }

    public function getAvailableManualAttDays(Request $request) {
        $lTypeId = $request->lTypeId;
        $rec_id = $request->rec_id;
        $empOrOthers = $request->empOrOthers;
        $approvedManualAtts = array();
        $allowedManualAttDays = DB::table('hr_leave_type')->where('lTypeId', $lTypeId)->first()->leave_days;

        if($empOrOthers == 1) {
            $approvedManualAtts = DB::table('emp_leave_apps')->select('rec_id', DB::raw('IFNULL(SUM(total_days),0) AS gross_total_days'))
            ->where('lTypeId', $lTypeId)->where('rec_id', $rec_id)->where('lStatus', 2)->first();
        } else {
            $approvedManualAtts = $this->db->query("SELECT IFNULL(SUM(total_days), 0) AS gross_total_days
                FROM std_leave_apps ela WHERE lTypeId = $lTypeId AND rec_id = $rec_id
                AND lStatus = 2")->row();
        }
        // echo $this->db->last_query();exit();
        if($approvedManualAtts) {
            $availableManualAttDays = ($allowedManualAttDays - $approvedManualAtts->gross_total_days);
            if ($availableManualAttDays <= $allowedManualAttDays) {
                echo json_encode(array('success' => 'OK', 'availableManualAttDays' => $availableManualAttDays));
            } else {
                echo json_encode(array('error' => 'No data found', 'availableManualAttDays' => ''));
            }
        } else {
            echo json_encode(array('error' => 'No data found', 'availableManualAttDays' => ''));
        }
    }

    public function store(Request $request) {
        $this->validate($request, [
            'rec_id' => 'required|int|max:10',
            'lTypeId' => 'required|int|max:10',
            'leave_start' => 'required|string|max:10',
            'leave_end' => 'required|string|max:10',
            'leave_description' => 'required|string|max:250',

            // 'leave_start' => 'date',
            // 'leave_end' => 'date',
            // 'date_field' => 'after:leave_start|before:leave_end',
        ]);
        if($request->leave_start > $request->leave_end) {
            return redirect()->route('leaves.index')->with(['alert-type' => 'error', 'message' => 'Date input error']);
        }
        $session_id = DB::table('organization_session')->orderBy('session_status', 'DESC')->first()->session_id;

        if($request->ela_id) {
            ManualAtt::findOrFail($request->ela_id)->update([
                'rec_id' => $request->rec_id,
                'lTypeId' => $request->lTypeId,
                'responsible_emp_id' => $request->responsible_emp_id,
                'leave_start' => $request->leave_start,
                'leave_end' => $request->leave_end,
                'leave_description' => $request->leave_description,
                'session_id' => $session_id,
                'edited_by' => Auth::user()->id,
                'edited_on' => date('Y-m-d H:i:s')
            ]);
            DB::table('emp_leave_apps_details')->where('ela_id', $request->ela_id)->delete();
            $ela_id = $request->ela_id;
        } else {
            ManualAtt::create([
                'rec_id' => $request->rec_id,
                'lTypeId' => $request->lTypeId,
                'responsible_emp_id' => $request->responsible_emp_id,
                'leave_start' => $request->leave_start,
                'leave_end' => $request->leave_end,
                'leave_description' => $request->leave_description,
                'session_id' => $session_id,
                'lStatus' => 2,
                'added_by' => Auth::user()->id,
                'added_on' => date('Y-m-d H:i:s')
            ]);
            $ela_id = DB::table('emp_leave_apps')->max('ela_id');
        }

        $start      =Carbon::parse($request->leave_start);
        $end        =Carbon::parse($request->leave_end);
        $date_diff  =$start->diffInDays($end);

        $detailData = array();
        $incr = 0; $comma = $leave_dates = '';
        for($i = 0; $i <= $date_diff; $i++) {
            $detailData[$incr] = array(
                'ela_id' => $ela_id,
                'leavedate' => (clone $start)->addDays($i)->format('Y-m-d')
            );
            $incr++;

            $leave_dates .= $comma . (clone $start)->addDays($i)->format('Y-m-d');
            $comma = ',';
        }
        if($detailData) {
            DB::table('emp_leave_apps_details')->insert($detailData);

            ManualAtt::findOrFail($ela_id)->update([
                'leave_dates' => $leave_dates,
                'total_days' => count(explode(",", $leave_dates))
            ]);
        }

        return redirect()->route('leaves.index')->with(['alert-type' => 'success', 'message' => 'ManualAtt successfully saved']);
    }

    public function edit(int $id) {
        return ManualAtt::findOrFail($id);
    }

    public function approve(int $ela_id): RedirectResponse {
        $dta = ManualAtt::findOrFail($ela_id);
        $msg = '';
        if($dta and $dta->lStatus < 2) {
            ManualAtt::findOrFail($ela_id)->update([
                'lStatus' => 2,
                'edited_by' => Auth::user()->id,
                'edited_on' => date('Y-m-d H:i:s')
            ]);
            $msg = 'ManualAtt successfully approved';
            return redirect()->back()->with(['alert-type' => 'success', 'message' => $msg]);
        } else {
            $msg = 'ManualAtt already approved / removed';
            return redirect()->back()->with(['alert-type' => 'error', 'message' => $msg]);
        }
    }

    public function destroy(int $id): RedirectResponse {
        ManualAtt::findOrFail($id)->delete();
        return redirect()->back()->with(['alert-type' => 'success', 'message' => 'ManualAtt successfully deleted']);
    }
}
