<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Carbon;
class ScanQR_controller extends Controller
{
          public function fetchTest(Request $request){
           $message = "OKOK";
            return $message;
           }
            public function PlaceWork(Request $request)
            {
                $distance = $request->input('distance');
                $lat = $request->input('lat');
                $log = $request->input('log');
                $selectColumns = [
                    'id',
                    'lat',
                    'log',
                    'no_zone',
                    'type_zone',
                    DB::raw("(
                        6371 * acos(
                            cos(radians($lat)) 
                            * cos(radians(lat)) 
                            * cos(radians(log) - radians($log)) 
                            + sin(radians($lat)) 
                            * sin(radians(lat))
                        )
                    ) AS distance")
                ];
            
                // Fetch the results with the distance condition
                $output = DB::connection('mysql')
                    ->table('place_works')
                    ->select($selectColumns)
                    ->havingRaw('distance < ?', [$distance])
                    ->orderBy('id', 'ASC') 
                    ->orderBy('distance', 'ASC') 
                    ->get();
                    // ->count();
            
                return $output;
            }
            public function scanQR(Request $request) {
                $currentDate = now()->format('Y-m-d');
                $AddcurrentDate = now()->addDay()->format('Y-m-d');
                $currentTime = now()->format('h:i:s');
                $time_table = 'N/A';
                $on_duty = '';
                $off_duty = '';
               
                 if ($currentTime >= '06:00:00' && $currentTime < '12:00:00'){
                    $time_table = 'Morning';
                    $on_duty = '07:30:00';
                    $off_duty = '12:00:00';
                    $timeDay="ពេលព្រឹក";
                } else {
                    $time_table = 'Afternoon';
                    $on_duty = '12:00:00';
                    $off_duty = '05:00:00';
                    $timeDay="ពេលថ្ងៃ";
                    }
               $output = DB::table('staff_PhnomPenh')
                ->where('time_table', $time_table)
                ->where('agency', $request->agency)
                ->whereBetween('date_work', [$currentDate, $AddcurrentDate])
                ->orderBy('id', 'DESC')
                ->select('id', 'date_work', 'time_table')
                ->first();
                $staffWork = ($output && $output->time_table == $time_table) ? 1 : 2;
                if ($staffWork == 1) {
                        DB::table('staff_PhnomPenh')
                            ->where('agency', $request->agency)
                            ->where('time_table', $time_table)
                            ->update([
                                'clock_out' => $currentTime,
                                'latitude' => $request->latitude,
                                'longitude' => $request->longitude,
                                'address' => $request->address,
                            ]);
                    } 
                    
                    // **CASE 2: INSERT**
                    else {
                        DB::table('staff_PhnomPenh')->insert([
                            'agency' => $request->agency, 
                            'date_work' => $currentDate,
                            'time_table' => $time_table,
                            'on_duty' => $on_duty,
                            'off_duty' => $off_duty,
                            'clock_in' => $currentTime,
                            'name' => $request->name,
                            'department' => "OUR COMPANY",
                            'latitude' => $request->latitude,
                            'longitude' => $request->longitude,
                            'address' => $request->address,
                        ]);
                    }
                  
                    
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                      CURLOPT_URL => 'https://api.telegram.org/bot7922031137:AAFfwFBUAaYY-870FKLl0qiMA28sqPlV_is/sendMessage',
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_ENCODING => '',
                      CURLOPT_MAXREDIRS => 10,
                      CURLOPT_TIMEOUT => 0,
                      CURLOPT_FOLLOWLOCATION => true,
                      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                      CURLOPT_CUSTOMREQUEST => 'GET',
                      CURLOPT_POSTFIELDS => json_encode(array(
                      'chat_id'=> "@groups_staff",   
                      'text' => $request->text . ($staffWork == 2?"Scan at " : "Scan again " ).$currentTime . " on " . $currentDate . "\nGoogleMap📍". "\nhttps://www.google.com/maps/@" . $request->latitude . "," . $request->longitude .",15z?q=".$request->latitude . "," . $request->longitude . "&markers=" . $request->latitude . "," . $request->longitude,
                   
                                      )),
                                       
                      CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json'
                      ),
                    ));
                    $response = curl_exec($curl);
                    curl_close($curl);
                
     //  'text' => $request->text . ($staffWork == 2 
                        //             ? ""
                        //             : "បានស្កេនម្ដងទៀតនៅថ្ងៃ ") . $currentDate . " ត្រូវនិងម៉ោង " . $currentTime . " នាពេល " . $timeDay.
                        //           "\nទីតាំងដែលបានស្ដិតនៅ📍".
                        //             "\nhttps://www.google.com/maps/@" . $request->latitude . "," . $request->longitude .",15z?q=".$request->latitude . "," . $request->longitude . "&markers=" . $request->latitude . "," . $request->longitude,
                    
               return response()->json([
                    "status" => "success",
                    "message" => $staffWork == 1 ? "Updated successfully" : "Inserted successfully"
                ]);
            }
            public function sendMessage(Request $request){
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                      CURLOPT_URL => 'https://api.telegram.org/bot7922031137:AAFfwFBUAaYY-870FKLl0qiMA28sqPlV_is/sendMessage',
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_ENCODING => '',
                      CURLOPT_MAXREDIRS => 10,
                      CURLOPT_TIMEOUT => 0,
                      CURLOPT_FOLLOWLOCATION => true,
                      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                      CURLOPT_CUSTOMREQUEST => 'GET',
                      CURLOPT_POSTFIELDS => json_encode(array(
                      'chat_id'=> "@groups_staff",   
                      'text'=> $request->text
                                  )),
                      CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json'
                      ),
                    ));
                    $response = curl_exec($curl);
                    curl_close($curl);
                    return "messsage Done!";
            
                }


}
