<?php
// Ensure database connection is present
if (!isset($con)) {
    include "../../../database_con.php";
}

$gender = 1;
// Fetch madrasa code from session or fallback
$madrasa_code = isset($_SESSION["madrasa_code"]) ? $_SESSION["madrasa_code"] : 59; 
$to_day = date("Y-m-d");
$current_time = date("H:i:s");

// Ensure session_year is set
if(!isset($session_year)) {
    $sql_year = mysqli_query($con, "SELECT year FROM `academic_year` where madrasa_code='$madrasa_code' order by year desc limit 1");
    if($row_year = mysqli_fetch_assoc($sql_year)) {
        $session_year = $row_year['year'];
    }
}

// 1. Time control
$abs_time_sql = mysqli_query($con, "SELECT `in_time_end`, `out_time_start` FROM `punch_in_out_time` where madrasa_code='$madrasa_code' AND gender='$gender' AND machine_no='1' limit 1 ");
$row_time = mysqli_fetch_assoc($abs_time_sql);

if ($row_time) {
    $in_time_end = $row_time['in_time_end'];
    
    // Check if current time is strictly after the allowed in_time_end
    if ($current_time > $in_time_end) {
        
        // 2. Control Once a Day execution (File Based Log)
        // Store log in the same directory using the madrasa_code
        $log_file = __DIR__ . DIRECTORY_SEPARATOR . "absence_sms_log_" . $madrasa_code . ".txt";
        $last_run_date = "";
        
        if (file_exists($log_file)) {
            $last_run_date = trim(file_get_contents($log_file));
        }
        
        // Check if SMS wasn't already sent today
        if ($last_run_date != $to_day) {
            
            // 3. SMS Configuration Check
            $config_sql = mysqli_query($con, "
                    SELECT token, url
                    FROM sms_control
                    WHERE madrasa_code = '$madrasa_code'
                      AND sms_idf = 11 AND gender='$gender'
                      AND status = 1
                    LIMIT 1
                ");
            
            if ($config_sql && mysqli_num_rows($config_sql) > 0) {
                $config = mysqli_fetch_assoc($config_sql);
                $token = $config['token'];
                $url = $config['url'];
                
                // 4. Gather Absent Students
                $sql = mysqli_query($con, "SELECT id, id_admission, name, mobile 
                FROM student_main_info_view smiv
                WHERE smiv.id NOT IN (SELECT idf FROM punch_records where DATE(punchTime) = '$to_day' AND punchMode='IN' AND madrasa_code='$madrasa_code' group by punch_records.idf) 
                AND smiv.admissionyear = '$session_year' AND smiv.off=0 AND smiv.madrasa_code='$madrasa_code' order by smiv.id asc;");

                if ($sql && mysqli_num_rows($sql) > 0) {
                    while ($student = mysqli_fetch_assoc($sql)) {
                        $mobile = $student['mobile'];
                        
                        // Construct the message body
                        $message = "সম্মানিত অভিভাবক, " . $student['name'] . " আজ মাদরাসায় অনুপস্থিত।";
                        
                        // Proceed to send SMS only if mobile is valid
                        if (strlen(trim($mobile)) >= 11) {
                            $data = [
                                'to'      => $mobile,
                                'message' => $message,
                                'token'   => $token
                            ];

                            $ch = curl_init();
                            curl_setopt_array($ch, [
                                CURLOPT_URL            => $url,
                                CURLOPT_POST           => true,
                                CURLOPT_POSTFIELDS     => http_build_query($data),
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_TIMEOUT        => 30,
                            ]);

                            $response = curl_exec($ch);
                            curl_close($ch);
                        }
                    }
                    
                    // 5. Update the log to ensure it doesn't send again today
                    file_put_contents($log_file, $to_day);
                    
                    echo "Absence SMS sent successfully for today!";
                } else {
                    echo "No absent students found today.";
                }
            } else {
                echo "SMS service is not activated or configured.";
            }
        } else {
            echo "SMS already sent today.";
        }
    } else {
        echo "It is not time yet. Allowed time is after: " . date("h:i:s A", strtotime($in_time_end));
    }
} else {
    echo "Time configurations missing.";
}

?>