<?php  
ini_set('display_errors', 1);  
error_reporting(E_ALL);  
date_default_timezone_set('Asia/Manila');  

// DB credentials  
$host = 'localhost';  
$user = 'root';  
$pass = '';  
$db   = 'school_checkin';  

$conn = new mysqli($host, $user, $pass, $db);  
if ($conn->connect_error) {  
    die("Connection failed: " . $conn->connect_error);  
}  

// GET data from QR  
$lrn    = isset($_GET['lrn'])    ? $conn->real_escape_string(trim($_GET['lrn']))    : '';  
$raw_name = isset($_GET['name']) ? $conn->real_escape_string(trim($_GET['name']))   : '';  
$grade  = isset($_GET['grade'])  ? $conn->real_escape_string(trim($_GET['grade']))  : '';  
$number = isset($_GET['number']) ? $conn->real_escape_string(trim($_GET['number'])) : '';  
$mobile = isset($_GET['mobile']) ? true : false;    

// 🧹 Remove birthday (last word) from name if present
$name_parts = preg_split('/\s+/', $raw_name);
if (count($name_parts) >= 2) {
    array_pop($name_parts); // Remove last word (assumed birthday)
}
$name = implode(' ', $name_parts);

$time     = date('Y-m-d H:i:s');  
$today    = date('Y-m-d');  
$justTime = date('H:i');  
$display  = "";  
$color    = "black";  
$session  = "";  
$column   = "";  

// SMS config
$api_key = 'd6ca064e18dff225d4e3909d1becaae4';
$sender  = 'SEMAPHORE';

function sendSMS($number, $message, $api_key, $sender) {
    if (preg_match('/^\d{11,}$/', $number)) {
        $number = '+63' . substr($number, 1);
    }

    $data = [
        'to' => $number,
        'message' => $message
    ];

    try {
        $ch = curl_init('https://sms.capiroso.site');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: 4e02fd2f-52f5-4aba-865f-fc1803bc0f62'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    } catch (Exception $e) {
        return 'Error: ' . $e->getMessage();
    }
}

// ⏱ Exact Time Range Logic
if ($justTime >= "05:00" && $justTime < "10:00") {
    $session = "Morning In";
    $column = "am_in";
} elseif ($justTime >= "10:00" && $justTime < "12:00") {
    $session = "Morning Out";
    $column = "am_out";
} elseif ($justTime >= "12:00" && $justTime < "14:00") {
    $session = "Afternoon In";
    $column = "pm_in";
} elseif ($justTime >= "14:00" && $justTime < "18:00") {
    $session = "Afternoon Out";
    $column = "pm_out";
} else {
    $session = "Outside Time";
    $column = null;
    $column = "pm_out";
}

if (!empty($lrn) && !empty($name) && !empty($grade) && $column) {
    $sql    = "SELECT * FROM checkins WHERE lrn='$lrn' AND scan_date='$today'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();

        if (!empty($row[$column])) {
            $display = "⚠️ $name ($grade) already scanned for $session.";
            $color = "orange";
        } else {
            $conn->query("UPDATE checkins SET $column = '$justTime' WHERE id = " . $row['id']);
            $display = "$name ($grade) <b>logged $session</b> at " . date('g:i:s A');
            $color = "#28a745";
            // sendSMS($number, "$name ($grade) $session at " . date('g:i A'), $api_key, $sender);
            $timing = $mobile ? strtoupper($column) : null;
        }
    } else {
        // First scan of the day
        $insert = "INSERT INTO checkins (lrn, name, grade, number, $column, scan_date)  
                   VALUES ('$lrn', '$name', '$grade', '$number', '$justTime', '$today')";
        if ($conn->query($insert) === TRUE) {
            $display = "$name ($grade) <b>first log: $session</b> at " . date('g:i:s A');
            $color = "#28a745";
// sendSMS($number, "$name ($grade) $session at " . date('g:i A'), $api_key, $sender);
            $timing = $mobile ? strtoupper($column) : null;
        } else {
            $display = "❗ Failed to insert.";
            $color = "red";
        }
    }
} else {
    $display = "❗ Missing or invalid QR data, or outside scan schedule.";
    $color = "red";
}
$conn->close();
if (!isset($timing)) {
    echo '<!DOCTYPE html>
<html>
<head>
    <title>Login/Logout Notification</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f1f1f1;
            text-align: center;
            padding: 50px;
        }
        .box {
            background: #fff;
            padding: 30px;
            border-radius: 15px;
            display: inline-block;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            max-width: 90%;
        }
        .box h2 {
            font-size: 22px;
            font-weight: bold;
            color: ' . $color . ';
        }
    </style>
</head>
<body>
    <div class="box">
        <h2>' . $display . '</h2>
    </div>
</body>
</html>';
} else {
    echo $timing;
}
?>
