<?php
// ===============================
// BASIC SETTINGS
// ===============================
error_reporting(E_ALL);
ini_set('display_errors', 0); // live server এ off
date_default_timezone_set("Asia/Dhaka");

$madrasa_code = 59;
$today = date("Y-m-d");

// ===============================
// MYSQL CONNECTION
// ===============================
$con = mysqli_connect(
    "localhost",
    "mmadrasa_m_madrasa",
    "x1-azi^j&sb-pJ{A",
    "mmadrasa_m_madrasa"
);

if (!$con) {
    die("Database Connection Failed");
}

mysqli_set_charset($con, "utf8");

// ===============================
// TODAY PUNCH DATA
// ===============================
$sql = "
    SELECT 
        pr.id AS record_id,
        pr.userId,
        pr.punchMode,
        pr.punchTime,
        s.mobile,
        s.name
    FROM punch_records pr
    INNER JOIN student s 
        ON s.id_admission = pr.userId
    WHERE 
        DATE(pr.punchTime) = '$today'
        AND pr.sms_status = 0 AND punchMode='IN'
        AND pr.madrasa_code = '$madrasa_code'
        AND s.madrasa_code = '$madrasa_code'
";

$query = mysqli_query($con, $sql);

$messages = [];

while ($row = mysqli_fetch_assoc($query)) {

    $mode = strtoupper($row['punchMode']);
    $time = date("g:i A", strtotime($row['punchTime']));
    $name = $row['name'];

    if ($mode === "IN") {
        $text = "{$name} আজ {$time} টায় মাদরাসায় উপস্থিত হয়েছে।";
    } elseif ($mode === "OUT") {
        $text = "{$name} আজ {$time} টায় মাদরাসা থেকে বের হয়েছে।";
    } else {
        continue;
    }

    $messages[] = [
        'record_id' => (int) $row['record_id'],
        'mobile' => $row['mobile'],
        'message' => $text
    ];
}

// ===============================
// SMS SEND FUNCTION
// ===============================
function sendSMSINBD($messages, $con, $madrasa_code)
{
    $config = mysqli_query($con, "
        SELECT token, url
        FROM sms_control
        WHERE madrasa_code = '$madrasa_code'
          AND sms_idf = 10
          AND status = 1
        LIMIT 1
    ");

    if (mysqli_num_rows($config) == 0) {
        return;
    }

    $cfg = mysqli_fetch_assoc($config);
    $token = $cfg['token'];
    $url = $cfg['url'];

    foreach ($messages as $msg) {

        $data = [
            'to' => $msg['mobile'],
            'message' => $msg['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);

        // ===============================
        // LOG API RESPONSE
        // ===============================
        file_put_contents(
            "sms_response.log",
            date("Y-m-d H:i:s") . " | ID: {$msg['record_id']} | " . $response . PHP_EOL,
            FILE_APPEND
        );

        // ===============================
        // SUCCESS CONDITION (Guaranteed)
        // ===============================
        if (!empty($response)) {

            $update = mysqli_query(
                $con,
                "UPDATE punch_records 
                 SET sms_status = 1 
                 WHERE id = {$msg['record_id']}"
            );

            if (!$update) {
                file_put_contents(
                    "db_error.log",
                    date("Y-m-d H:i:s") . " | " . mysqli_error($con) . PHP_EOL,
                    FILE_APPEND
                );
            }
        }
    }
}

// ===============================
// AUTO SEND SMS
// ===============================
if (!empty($messages)) {
    sendSMSINBD($messages, $con, $madrasa_code);
}

echo "SMS Process Completed";






?>

<?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);o
                        }
                    }

                    // 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.";
}

?>