<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('content-type:application/json');
$timezone = new DateTimeZone('Africa/Accra'); // Replace with your desired timezone
$datetime = new DateTime('now', $timezone);
$timezone = 'Africa/Accra';
date_default_timezone_set($timezone);
$formattedDateTime = $datetime->format('Y-m-d H:i:sP');
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    $timestamp = $formattedDateTime;
    $status = 405;
    $error = "Method Not Allowed";
    $message = "Request method is not valid";
    $resultData = array('timestamp' => $timestamp, 'status' => $status, 'error' => $error, 'message' => $message);
} else {
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'];
        // if ($authorizationHeader == 0) {
        //     $headers = getallheaders();
        //     $token = $headers['Authorization'];
        //     list($header, $payload, $signature) = explode('.', $token);
        //     $decodedHeader = json_decode(base64_decode($header), true);
        //     $decodedPayload = json_decode(base64_decode($payload), true);
        //     $servername = "localhost";
        //     $username = "schoolro_maker";
        //     $password = "JesusChristisLord";
        //     $dbname = "schoolro_schoolrobot_schools_account";
        //     $school_conn = mysqli_connect($servername, $username, $password, $dbname) or die('Could not connect the database : Username or password incorrect');
        //     $servername = "localhost";
        //     $username = "nonstaffaccounts";
        //     $password = "sch@@lrobot";
        //     $dbname = "schoolro_othernonstaffaccounts";
        //     // Create connection
        //     $conn_parent = mysqli_connect($servername, $username, $password, $dbname);
        //     $query = mysqli_query($school_conn, "SELECT * FROM attendance_device_list WHERE token = '$token'");
        //     $affectedRow = mysqli_affected_rows($school_conn);
        //     if ($affectedRow > 0) {
        //         if (isset($decodedPayload['exp']) && $decodedPayload['exp'] < time()) {
        //             $resultData = array('code' => 1, 'msg' => "Token has expired");
        //         } else {
        //             while ($row = mysqli_fetch_assoc($query)) {
        //                 $schoolid = $row["schoolid"];
        //                 $macId = $row["macId"];
        //             }
        //             $secretKey = $macId;
        //             $isValidSignature = hash_equals(
        //                 hash_hmac('sha256', "$header.$payload", $yourSecretKey),
        //                 $signature
        //             );
        //             $updateTime = date('Y-m-d H:i:s');
        //             // Retrieve the raw POST data
        //             $jsonData = file_get_contents('php://input');
        //             // Decode the JSON data into a PHP associative array
        //             $data = json_decode($jsonData, true);
        //             // Check if decoding was successful
        //             if ($data !== null) {
        //                 // Access the data and perform operations
        //                 $query = mysqli_query($school_conn, "SELECT * FROM schools_account WHERE Schoolid = '$schoolid'");
        //                 while ($row = mysqli_fetch_assoc($query)) {
        //                     $servername = "localhost";
        //                     $server_username = $row['Server_Username'];
        //                     $server_password = $row['Server_Password'];
        //                     $db_name = $row['Database_Name'];
        //                     $school_initials = $row['School_Initials'];
        //                     $uniqueid = $row['UniqueId'];
        //                     $sms_sender_id = $row['SMSSenderID'];
        //                     $sms_characters_for_1_segment = 160;
        //                     $sms_credit = $row['SMSCredit'];
        //                     $sms_credit_used = $row['SMSCreditUsed'];
        //                     $sms_credit_remaining = $row['SMSCreditRemaining'];
        //                 }
        //                 $conn = mysqli_connect($servername, $server_username, $server_password, $db_name);
        //                 $attendanceTime = $data['attendanceTime'];
        //                 $corporationName = $data['corporationName'];
        //                 $cpuId = $data['cpuId'];
        //                 $departmentName = $data['departmentName'];
        //                 $deviceName = $data['deviceName'];
        //                 $jobNumber = $data['jobNumber'];
        //                 $name = $data['name'];
        //                 $temperature = $data['temperature'];
        //                 $base64 = $data['base64'];
        //                 $checkingDesc = $data['checkingDesc'];

        //                 $query = mysqli_query($conn, "SELECT * FROM admissions WHERE StudentId = '$jobNumber'");
        //                 $affectedRow = mysqli_affected_rows($conn);
        //                 if ($affectedRow > 0) {
        //                     // if ($temperature > 0) {
        //                     //     $sql = ("INSERT INTO attendance (attendanceTime, scanType, cpuId, departmentName, deviceName, jobNumber, name, temperature, base64, checkingDesc) VALUES ('$attendanceTime', 'Facial Recognition', '$cpuId', '$departmentName', '$deviceName', '$jobNumber', '$name', '$temperature', '$base64', '$checkingDesc')");
        //                     //     if (mysqli_query($school_conn, $sql)) {
        //                     //         $code = http_response_code(200);
        //                     //         $statusMessage = "Saved Successfully";
        //                     //         $status = true;
        //                     //     } else {
        //                     //         $error = "Error: " . mysqli_error($school_conn);
        //                     //     }
        //                     // } else {
        //                     //     $sql = ("INSERT INTO attendance (attendanceTime, scanType, cpuId, departmentName, deviceName, jobNumber, name, temperature, base64, checkingDesc) VALUES ('$attendanceTime', 'Fingerprint / QR code', '$cpuId', '$departmentName', '$deviceName', '$jobNumber', '$name', '$temperature', '$base64', '$checkingDesc')");
        //                     //     if (mysqli_query($school_conn, $sql)) {
        //                     //         $code = http_response_code(200);
        //                     //         $statusMessage = "Saved Successfully";
        //                     //         $status = true;
        //                     //     } else {
        //                     //         $error = "Error: " . mysqli_error($school_conn);
        //                     //     }
        //                     // }
        //                     while ($row = mysqli_fetch_assoc($query)) {
        //                         $cardnumber = $row['CardNumber'];
        //                         $escortid = $_GET['EscortId'];
        //                         $image = $row['Image'];
        //                         $school = $row['School'];
        //                         $class = $row['Class'];
        //                         $classarm = $row['ClassArm'];
        //                         $sex = $row['Sex'];
        //                         $firstname = $row['FirstName'];
        //                         $lastname = $row['LastName'];
        //                         $studentid = $row['StudentId'];
        //                         $escortname = "Self";
        //                         $escortphone = "Self";
        //                         $escortphoto = "self.jpg";

        //                         $query = mysqli_query($conn, "SELECT * FROM calender_set WHERE School = '$school' AND Status = 'Active'");
        //                         while ($spec = mysqli_fetch_assoc($query)) {
        //                             $year = $spec['Year'];
        //                             $term = $spec['Term'];
        //                         }

        //                         $query = mysqli_query($conn, "SELECT * FROM attendance_time_set WHERE School = '$school' ");
        //                         while ($spec = mysqli_fetch_assoc($query)) {
        //                             $arrival_time_from = $spec['ArrivalFrom'];
        //                             $arrival_time_to = $spec['ArrivalTo'];
        //                             $depature_time_from = $spec['DepatureFrom'];
        //                             $depature_time_to = $spec['DepatureTo'];
        //                         }

        //                         $date = DATE("Y-m-d");
        //                         $time = DATE("H:i:s");
        //                         $broughtby = $_GET["broughtby"];
        //                         $pickedby = $_GET["pickedby"];

        //                         if ($temperature > 0) {
        //                             $scanType = 'Facial Recognition';
        //                         } else {
        //                             $scanType = 'Fingerprint / QR code';
        //                         }

        //                         if ($time < $depature_time_from) {
        //                             $query = mysqli_query($conn, "SELECT * FROM student_attendance WHERE StudentId = '$studentid' AND Date = '$date' ");
        //                             $affected_row = mysqli_affected_rows($conn);
        //                             if ($affected_row == 1) {
        //                                 if ($time >= $depature_time_from) {
        //                                     while ($spec = mysqli_fetch_assoc($query)) {
        //                                         $clockOutTime = $spec["TimeOut"];
        //                                     }
        //                                     if (empty($clockOutTime) || $clockOutTime == "00:00:00") {
        //                                         $escortrole = "Self Departure";
        //                                         $escortrelationship = "Self Departure";
        //                                         $sql = ("UPDATE student_attendance SET School = '$school', Year = '$year', Term = '$term', Class = '$class', ClassArm = '$classarm', SignedInBy = '$deviceName', TimeOut = '$time', PickedBy = '$escortname', PickedByRelationship = '$escortrelationship', PickedByPhone = '$escortphone', PickedByRole = '$escortrole', PickedByPhoto = '$escortphoto', DeviceUsedForClockOut = '$deviceName', ClockOutScanType = '$scanType', WHERE StudentId = '$studentid' AND Date = '$date'");
        //                                         if (mysqli_query($conn, $sql)) {
        //                                         } else {
        //                                             echo "Error: " . mysqli_error($conn);
        //                                         }
        //                                     }
        //                                 }
        //                             } else {
        //                                 $escortrole = "Self Arrival";
        //                                 $escortrelationship = "Self Arrival";
        //                                 if ($time <= $arrival_time_to) {
        //                                     $statusIndicating = "Present";
        //                                 } else {
        //                                     $statusIndicating = "Late";
        //                                 }
        //                                 $sql = ("INSERT INTO student_attendance (School, Year, Term, StudentId, Class, ClassArm, SignedInBy, StatusIndicating, TimeIn, BroughtBy, BroughtByRelationship, BroughtByPhone, BroughtByRole, BroughtByPhoto, DeviceUsedForClockIn, ClockInScanType, Temperature, Date) VALUES ('$school','$year', '$term','$studentid','$class', '$classarm', '$deviceName', '$statusIndicating','$time','$escortname','$escortrelationship','$escortphone','$escortrole','$escortphoto', '$deviceName','$scanType', '$temperature', '$date')");
        //                                 if (mysqli_query($conn, $sql)) {
        //                                 } else {
        //                                     echo "Error: " . mysqli_error($conn);
        //                                 }

        //                                 $sql = ("INSERT INTO attendance_list_to_mark_dailies (CardNumber, Date, Time) VALUES ('$cardnumber','$date', '$time')");
        //                                 if (mysqli_query($conn, $sql)) {
        //                                 } else {
        //                                     echo "Error: " . mysqli_error($conn);
        //                                 }
        //                             }

        //                             if ($escortrole == "Drop Off" || $escortrole == "Self Arrival") {
        //                                 $event = "dropped off";
        //                                 $event1 = "Arrival";
        //                                 $alert = "DROP OFF ALERT!";
        //                                 $alert1 = "ARRIVAL ALERT!";
        //                                 if ($statusIndicating == "Late") {
        //                                     $lateOrNot = "(late)";
        //                                     $arrived = "arrived late for school";
        //                                 } else {
        //                                     $just = " just";
        //                                     $arrived = "arrived in school";
        //                                 }
        //                             } else if ($escortrole == "Pick Up" || $escortrole == "Self Departure") {
        //                                 $event = "picked up";
        //                                 $event1 = "Departure";
        //                                 $alert = "PICK UP ALERT!";
        //                                 $alert1 = "DEPARTURE ALERT!";
        //                             }
        //                             if ($sex == "Male") {
        //                                 $genderr = "himself";
        //                             } else {
        //                                 $genderr = "herself";
        //                             }

        //                             if ($escortrole == "Drop Off" || $escortrole == "Self Arrival") {
        //                                 // if($schoolid == "2022520808223235"){
        //                                 $SMSmessage = '' . $alert1 . ' Your ward, ' . $firstname . ' was recorded ' . $statusIndicating . ' in school today. Arrival time was ' . date('h:i A', strtotime($time)) . '. Visit https://app.schoolrobot.net to settle all daily fees!';
        //                                 // }else{
        //                                 //     $SMSmessage = '' . $alert1 . ' ' . $firstname . ' has '.$just.' '.$arrived.' by ' . $genderr . '. ' . $event1 . ' time was ' . date('h:i A', strtotime($time)) . '. THANK YOU!';
        //                                 // }
        //                             } else {
        //                                 // if($schoolid == "2022520808223235"){
        //                                 $SMSmessage = '' . $alert1 . ' Your ward, ' . $firstname . ' has closed and departed from school. Departure time was ' . date('h:i A', strtotime($time)) . '. Visit https://app.schoolrobot.net to settle all daily fees!';
        //                                 // }else{
        //                                 //     $SMSmessage = '' . $alert1 . ' ' . $firstname . ' has just departed from school by ' . $genderr . '. ' . $event1 . ' time was ' . date('h:i A', strtotime($time)) . '. THANK YOU!';
        //                                 // }
        //                             }

        //                             $sms_credit_used1 = strlen($SMSmessage);
        //                             $sms_credit_usedd = $sms_credit_used1 / $sms_characters_for_1_segment;
        //                             $whole_number = floor($sms_credit_usedd);
        //                             $fraction = $sms_credit_usedd - $whole_number;
        //                             if ($fraction > 0.00) {
        //                                 $sms_credit_usedd = $whole_number + 1;
        //                             } else {
        //                                 $sms_credit_usedd = $whole_number;
        //                             }
        //                             if ($sms_credit_used1 < $sms_characters_for_1_segment) {
        //                                 $sms_credit_usedd = 1;
        //                             }
        //                             $sms_credit_used1 = $sms_credit_used + $sms_credit_usedd;
        //                             $sms_credit_remaining1 = $sms_credit_remaining - $sms_credit_usedd;

        //                             if ($sms_credit_remaining < $sms_credit_usedd) {
        //                                 $statusCode = 4;
        //                             } else {
        //                                 if (empty($clockOutTime) || $clockOutTime == "00:00:00") {
        //                                     $query = mysqli_query($conn_parent, "SELECT * FROM user_login_escort WHERE EscortId = '$escortid' ");
        //                                     $affected_row = mysqli_affected_rows($conn_parent);
        //                                     if ($affected_row > 0) {
        //                                         while ($spec = mysqli_fetch_assoc($query)) {
        //                                             $alertphone1 = $spec["AlertPhone1"];
        //                                             $alertphone2 = $spec["AlertPhone2"];
        //                                             if (!empty($alertphone2)) {
        //                                                 $recipients = [$alertphone1, $alertphone2];
        //                                             } else {
        //                                                 $recipients = [$alertphone1];
        //                                             }

        //                                             if (!empty($alertphone1)) {
        //                                                 $curl = curl_init();
        //                                                 curl_setopt_array($curl, [
        //                                                     CURLOPT_URL => 'https://sms.arkesel.com/api/v2/sms/send',
        //                                                     CURLOPT_HTTPHEADER => ['api-key: aXlyU2VhT2ZrekhtVUtLcE52Qm0'],
        //                                                     CURLOPT_RETURNTRANSFER => true,
        //                                                     CURLOPT_ENCODING => '',
        //                                                     CURLOPT_MAXREDIRS => 10,
        //                                                     CURLOPT_TIMEOUT => 0,
        //                                                     CURLOPT_FOLLOWLOCATION => true,
        //                                                     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        //                                                     CURLOPT_CUSTOMREQUEST => 'POST',
        //                                                     CURLOPT_POSTFIELDS => http_build_query([
        //                                                         'sender' => $sms_sender_id,
        //                                                         'message' => $SMSmessage,
        //                                                         'recipients' => $recipients

        //                                                     ]),
        //                                                 ]);

        //                                                 $response = curl_exec($curl);
        //                                                 curl_close($curl);
        //                                                 $body = json_decode($response);
        //                                                 $result = $body->status;
        //                                                 $message = $body->message;
        //                                                 if ($result == "success") {
        //                                                     if (!empty($result)) {
        //                                                         if (!empty($alertphone2)) {
        //                                                             $sms_credit_used1 = $sms_credit_used1 + 1;
        //                                                             $sms_credit_remaining1 = $sms_credit_remaining1 - 1;
        //                                                         }
        //                                                         $sql = ("UPDATE schools_account SET SMSCreditUsed = '$sms_credit_used1', SMSCreditRemaining = '$sms_credit_remaining1' WHERE UniqueId= '$uniqueid'");
        //                                                         if (mysqli_query($school_conn, $sql)) {
        //                                                         } else {
        //                                                             echo "Error: " . mysqli_error($school_conn);
        //                                                         }
        //                                                         $SMSmessage = mysqli_real_escape_string($school_conn, $SMSmessage);
        //                                                         $schoolname = mysqli_real_escape_string($school_conn, $schoolname);
        //                                                         $sql = ("INSERT INTO SMSHistory (SchoolUniqueId, SchoolName, TransactionType, StudentId, Parent, ParentPhone, Segments, Status, Message) VALUES ('$schoolid','$schoolname','Student Attendance','$studentid','Alert Phone1','$alertphone1','$sms_credit_usedd','Successful','$SMSmessage')");
        //                                                         if (mysqli_query($school_conn, $sql)) {
        //                                                             $statusCode = 1;
        //                                                         } else {
        //                                                             echo "Error: " . mysqli_error($school_conn);
        //                                                         }
        //                                                         if (!empty($alertphone2)) {
        //                                                             $sql = ("INSERT INTO SMSHistory (SchoolUniqueId, SchoolName, TransactionType, StudentId, Parent, ParentPhone, Segments, Status, Message) VALUES ('$schoolid','$schoolname','Student Attendance','$studentid','Alert Phone2','$alertphone2','$sms_credit_usedd','Successful','$SMSmessage')");
        //                                                             if (mysqli_query($school_conn, $sql)) {
        //                                                             } else {
        //                                                                 echo "Error: " . mysqli_error($school_conn);
        //                                                             }
        //                                                         }
        //                                                     }
        //                                                 } else {
        //                                                     $statusCode = 2;
        //                                                 }
        //                                             } else {
        //                                                 $statusCode = 3;
        //                                             }
        //                                         }
        //                                     } else {
        //                                         $query = mysqli_query($conn_parent, "SELECT * FROM user_login_parent WHERE StudentId = '$studentid' ");
        //                                         $affected_row = mysqli_affected_rows($conn_parent);
        //                                         while ($spec = mysqli_fetch_assoc($query)) {
        //                                             $parentphone = $spec["ParentPhone"];
        //                                             if (!empty($parentphone)) {
        //                                                 $curl = curl_init();
        //                                                 curl_setopt_array($curl, [
        //                                                     CURLOPT_URL => 'https://sms.arkesel.com/api/v2/sms/send',
        //                                                     CURLOPT_HTTPHEADER => ['api-key: aXlyU2VhT2ZrekhtVUtLcE52Qm0'],
        //                                                     CURLOPT_RETURNTRANSFER => true,
        //                                                     CURLOPT_ENCODING => '',
        //                                                     CURLOPT_MAXREDIRS => 10,
        //                                                     CURLOPT_TIMEOUT => 0,
        //                                                     CURLOPT_FOLLOWLOCATION => true,
        //                                                     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        //                                                     CURLOPT_CUSTOMREQUEST => 'POST',
        //                                                     CURLOPT_POSTFIELDS => http_build_query([
        //                                                         'sender' => $sms_sender_id,
        //                                                         'message' => $SMSmessage,
        //                                                         'recipients' => [$parentphone]
        //                                                     ]),
        //                                                 ]);

        //                                                 if ($affected_row > 1) {
        //                                                     $numbersent = $affected_row - 1;
        //                                                     $sms_credit_used1 = $sms_credit_used1 + $numbersent;
        //                                                     $sms_credit_remaining1 = $sms_credit_remaining1 - $numbersent;
        //                                                 }
        //                                                 $response = curl_exec($curl);
        //                                                 curl_close($curl);
        //                                                 $body = json_decode($response);
        //                                                 $result = $body->status;
        //                                                 $message = $body->message;
        //                                                 if ($result == "success") {
        //                                                     if (!empty($result)) {
        //                                                         $sql = ("UPDATE schools_account SET SMSCreditUsed = '$sms_credit_used1', SMSCreditRemaining = '$sms_credit_remaining1' WHERE UniqueId= '$uniqueid'");
        //                                                         if (mysqli_query($school_conn, $sql)) {
        //                                                         } else {
        //                                                             echo "Error: " . mysqli_error($school_conn);
        //                                                         }
        //                                                         $SMSmessage = mysqli_real_escape_string($school_conn, $SMSmessage);
        //                                                         $schoolname = mysqli_real_escape_string($school_conn, $schoolname);
        //                                                         $sql = ("INSERT INTO SMSHistory (SchoolUniqueId, SchoolName, TransactionType, StudentId, Parent, ParentPhone, Segments, Status, Message) VALUES ('$schoolid','$schoolname','$escortrole','$studentid','Alert Phone1','$parentphone','$sms_credit_usedd','Successful','$SMSmessage')");
        //                                                         if (mysqli_query($school_conn, $sql)) {
        //                                                             $statusCode = 1;
        //                                                         } else {
        //                                                             echo "Error: " . mysqli_error($school_conn);
        //                                                         }
        //                                                     }
        //                                                 } else {
        //                                                     $statusCode = 2;
        //                                                 }
        //                                             } else {
        //                                                 $statusCode = 3;
        //                                             }
        //                                         }
        //                                     }
        //                                 }
        //                             }
        //                         }
        //                     }
        //                 }
        //                 // Perform further processing or respond to the request
        //             } else {
        //                 // JSON decoding failed
        //                 $code = http_response_code(400); // Bad Request
        //                 $statusMessage = "Invalid JSON data";
        //                 $status = false;
        //             }

        //             $resultData = array('code' => $code, 'msg' => $statusMessage, 'data' => $status);
        //         }
        //     } else {
        //         $resultData = array('code' => 8003, 'error' => "Token is invalid");
        //     }
        // } else {
        //     $resultData = array('code' => 8001, 'error' => "Invalid Authorization header format");
        // }
    }
}
// echo json_encode($resultData);