<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class NotificationController extends Controller
{
    //Notification
    public function saveToken(Request $request) {
        $user = auth()->user();
        auth()->user()->update(['device_token'=>$request->token]);
        return response()->json(['token saved successfully.']);
    }

    public function sendNotification(Request $request) {
        // Execute the command
        // Artisan::call('notification:breeding');

        return response()->json(['send notification successfully.']);
    }
    public function test() {
        echo 'attendance';
    }
    public function auto_attendance(
        // Request $request
        ) {
        date_default_timezone_set("Asia/Dhaka");
        // exit('asdf');
        // $this->form_validation->set_rules('reg_id[]', 'students', 'trim|required');
        // $this->form_validation->set_rules('checktime[]', 'attendance time', 'trim|required');

        // if ($this->form_validation->run() == FALSE) {
        //     echo json_encode(array('error' => validation_errors()), JSON_HEX_TAG);
        //     echo json_encode(array('error' => 'validation_errors()'));
        //     echo 'validation_errors()';
        // } else {

        $reg_id = //array("24010001", "24050001"); // $this->input->post('reg_id');
        $checktime = //array(date('Y-m-d')." 14:51:16", date('Y-m-d')." 13:51:16"); // $this->input->post('checktime');
		$submited_reporting_id = array(); //array("1042603202409240311011", "1042603202409240311012"); // $this->input->post('reporting_id');

        $cntr = 1;

        $employees = DB::table('employees as emp')->orderBy('emp.employee_no', 'ASC')->get();
        foreach ($employees as $key => $value) {
            if($cntr > 60) {
                $cntr = 1;
            }
            $reg_id[$key]               = $value->employee_no;
            $checktime[$key]            = date('Y-m-d')." 09:" . sprintf("%02d", $cntr) . ":16";
            $submited_reporting_id[$key]= '1042603202409240311'.sprintf("%03d", ($key+1));
            $cntr++;
        }

        // $reg_id = $request->reg_id;
        // $checktime = $request->checktime;
        // $submited_reporting_id = $request->reporting_id;

        $TotalNumberOfEntry = count($reg_id);
        if ($TotalNumberOfEntry > 0) {
            $current_time = date('Y-m-d H:i:s');
            $close_time = date('Y-m-d 22:00:00');
            $close_time_morning = date('Y-m-d 22:00:00');
            $close_time_day = date('Y-m-d 22:00:00');
            if ($current_time < $close_time) {
                $att_data = $att_data2 = $reporting_id = array();
                $checktime1 = explode(" ", $checktime[0]);
                $att_date = $checktime1[0];

                $session_id = DB::table('organization_session')->selectRaw('MAX(session_id) AS session_id')->where('session_status', 1)->first()->session_id;

                $savedData = DB::Table('student_attendance')->select('student_reg')
                ->where('att_date', 'LIKE', $att_date.'%')->where('session_id', $session_id) // ->orWhere('bookname','LIKE','%'.$book[1].'%')
                ->get();

                if ($savedData) {
                    foreach ($savedData as $key => $value) {
                        $att_data[$key] = $value->student_reg;
                    }
                }

                // DB::enableQueryLog();
                $savedData2 = DB::Table('staff_attendance')->select('reg_id', 'reporting_id')
                ->where('att_date', 'LIKE', $att_date.'%')->where('session_id', '=',  $session_id)
                ->get();
                // dd(DB::getQueryLog()); exit;
                // return $savedData2;
                if ($savedData2) {
                    foreach ($savedData2 as $key => $value) {
                        $att_data2[$key] = $value->reg_id;
						$reporting_id[$key] = $value->reporting_id;
                    }
                }

                $DetailData = $reg_id_array = $DetailData2 = $staff_reg_array2 = array();
                $incr = $incr1 = $incr2 = 0;
                $strng = $str = "";
                for ($i = 0; $i < $TotalNumberOfEntry; $i++) {
                    // if (!in_array($reg_id[$i], $att_data) and ! in_array($reg_id[$i], $reg_id_array)
                    //         and $reg_id[$i] and $checktime[$i]  and ( strlen("$reg_id[$i]") > 8)) {
                    //     $section_shift = $this->db->query("SELECT cs.section_shift
                    //         FROM student_info si
                    //         JOIN student_record sr ON si.student_id = sr.student_id
                    //         JOIN class_section cs ON cs.section_id = sr.section_id
                    //         WHERE sr.rec_status = 'open' AND si.student_reg = $reg_id[$i]")
                    //         ->row('section_shift');

                    //     if ((($section_shift == 'Morning') and ( $current_time < $close_time_morning))
                    //             or ( ($section_shift == 'Day') and ( $current_time < $close_time_day))) {

                    //         $reg_id_array[$incr1] = $reg_id[$i];
                    //         $DetailData[$incr1]['reg_id'] = $reg_id[$i];
                    //         $DetailData[$incr1]['att_date'] = $checktime[$i];
                    //         $DetailData[$incr1]['session_id'] = $session_id;
                    //         $DetailData[$incr1]['att_status'] = 1;
                    //         $incr1++;
                    //     }
                    // } else

                    if (!in_array($submited_reporting_id[$i], $reporting_id) and !in_array($submited_reporting_id[$i], $staff_reg_array2)
                            and $reg_id[$i] and $checktime[$i]  and ( strlen("$reg_id[$i]") <= 8)) {

                        $staff_reg_array2[$incr2] = $submited_reporting_id[$i];
                        $DetailData2[$incr2]['reg_id'] = $reg_id[$i];
                        $DetailData2[$incr2]['att_date'] = $checktime[$i];
                        $DetailData2[$incr2]['session_id'] = $session_id;
                        $DetailData2[$incr2]['att_status'] = 1;
						$DetailData2[$incr2]['reporting_id'] = $submited_reporting_id[$i];
                        $incr2++;
                    } else {
                        //NOTHING TO DO
                    }
                }
                // return $DetailData2; exit;
                DB::beginTransaction();
                if ($DetailData) {
                    DB::table('student_attendance')->insert($DetailData);
                }
                if ($DetailData2) {
                    DB::table('staff_attendance')->insert($DetailData2);
                }

                if (DB::transactionLevel() > 0) {
                    DB::commit();
                    echo json_encode(array('success' => 'Successfully Done. !!!!!!!'));
                } else {
                    DB::rollBack();
                    echo json_encode(array('error' => 'Not saved!!!. Please try again !!!'));
                }
            }
        } else {
            echo json_encode(array('error' => 'Data Empty1!!!'));
        }
    }
}
