<?php

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

use App\Http\Controllers\Controller;
use App\Models\Hr\Attend\Leave;
use App\Models\User;
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;
use Illuminate\Support\Facades\Storage;

class LeaveController extends Controller
{
    public function index() {

        $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 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 getAvailableLeaveDays(Request $request) {
        $lTypeId = $request->lTypeId;
        $rec_id = $request->rec_id;
        $empOrOthers = $request->empOrOthers;
        $approvedLeaves = array();
        $allowedLeaveDays = DB::table('hr_leave_type')->where('lTypeId', $lTypeId)->first()->leave_days;

        if($empOrOthers == 1) {
            $approvedLeaves = 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 {
            $approvedLeaves = $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($approvedLeaves) {
            $availableLeaveDays = ($allowedLeaveDays - $approvedLeaves->gross_total_days);
            if ($availableLeaveDays <= $allowedLeaveDays) {
                echo json_encode(array('success' => 'OK', 'availableLeaveDays' => $availableLeaveDays));
            } else {
                echo json_encode(array('error' => 'No data found', 'availableLeaveDays' => ''));
            }
        } else {
            echo json_encode(array('error' => 'No data found', 'availableLeaveDays' => ''));
        }
    }

    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) {
            Leave::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 {
            Leave::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' => 1,
                '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);

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


        if ($request->has('document_reference')) {
            $docData = DB::table('emp_leave_apps_documents')->where('ela_id', $ela_id)->get();
            if ($docData) {
                foreach ($docData as $val) {
                    // if (Storage::disk('public')->exists('leave_documents/'.$val->document_reference)) {
                    //     Storage::disk('public')->delete('leave_documents/'.$val->document_reference);
                    // }
                    $fileWithPath = $_SERVER['DOCUMENT_ROOT'].'/storage/leave_documents/'.$val->document_reference;
                    if(file_exists("$fileWithPath")) {
                        unlink("$fileWithPath");
                    }
                    // if ($val->document_reference && Storage::exists('public/leave_documents/'.$val->document_reference)) {
                    //     Storage::delete('public/leave_documents/'.$val->document_reference);
                    // }
                    // unlink("$fileWithPath");
                    // return $fileWithPath; exit;
                }
                DB::table('emp_leave_apps_documents')->where('ela_id', $ela_id)->delete();
            }

            foreach ($request->document_reference as $ke => $images) {
                $imageName = time().$images->getClientOriginalName();
                $images->move(storage_path('app/public/leave_documents'), $imageName);// Eta OK Ace
                // $imageName = $this->uploadOne($images, 'employee_images');// Eta Server e Problem Kore

                $documentData[$ke] = array(
                    'ela_id' => $ela_id,
                    'document_reference' => $imageName
                );
            }
            DB::table('emp_leave_apps_documents')->insert($documentData);
        }
        // return $asdf ; exit;
        return redirect()->route('leaves.index')->with(['alert-type' => 'success', 'message' => 'Leave successfully saved ']);
    }

    public function show(int $ela_id): View {

        $leaveDocuments = DB::table('emp_leave_apps_documents')->where('ela_id', $ela_id)->get();
        // $jobsRecord = Employee::with('employeeRecords')->with('designation')->with('department')->where('id', $id)->get();
        // echo '<pre>'; print_r($employee); //exit;
         $lvData = DB::table('employees as ei')->join('employees_records as er', 'er.employee_id', '=', 'ei.id')
         ->join('emp_leave_apps as ela', 'ela.rec_id', '=', 'er.rec_id')
         ->leftJoin('organizations as org', 'org.id', '=', 'ei.organization_id')
         ->leftJoin('organizations as brn', 'brn.id', '=', 'er.rec_designation')
         ->leftJoin('designations as dsg', 'dsg.id', '=', 'er.rec_designation')
         ->leftJoin('departments as dpt', 'dpt.department_id', '=', 'er.rec_department')
         ->leftJoin('hr_leave_type as elt', 'elt.lTypeId', '=', 'ela.lTypeId')
         ->leftJoin('employees as resp', 'resp.id', '=', 'ela.responsible_emp_id')
         ->select('ela.*', 'ei.*', 'dsg.name AS designation_name', 'dpt.department_name',
         'org.name AS org_name', 'brn.name AS branch_name', 'elt.leave_type_name', 'resp.employee_name AS resp_name')
         ->where('ela.ela_id', $ela_id)->first();

        return view('backend.hr.attend.leave_show', compact('leaveDocuments', 'lvData'));
    }

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

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

    public function destroy(int $id): RedirectResponse {
        $docData = DB::table('emp_leave_apps_documents')->where('ela_id', $ela_id)->get();
        if ($docData) {
            foreach ($docData as $val) {
                $fileWithPath = $_SERVER['DOCUMENT_ROOT'].'/storage/leave_documents/'.$val->document_reference;
                if(file_exists("$fileWithPath")) {
                    unlink("$fileWithPath");
                }
            }
            DB::table('emp_leave_apps_documents')->where('ela_id', $ela_id)->delete();
        }

        Leave::findOrFail($id)->delete();
        return redirect()->back()->with(['alert-type' => 'success', 'message' => 'Leave successfully deleted']);
    }
}
