<?php
// Aktifkan error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt');

// Pastikan tidak ada output sebelum header JSON
if (ob_get_length()) ob_clean();

include "config.php";
include "telegram_config.php";
session_start();
date_default_timezone_set('Asia/Jakarta');

// Set header JSON
header('Content-Type: application/json');

// DEBUG - Catat request
$debug_log = "=== REQUEST BARU ===\n";
$debug_log .= "Waktu: " . date('Y-m-d H:i:s') . "\n";
$debug_log .= "GET: " . print_r($_GET, true) . "\n";
$debug_log .= "SESSION: " . print_r($_SESSION, true) . "\n";
file_put_contents(__DIR__ . '/debug_telegram.log', $debug_log, FILE_APPEND);

// Hak akses
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru', 'siswa', 'wali_kelas'])) {
    $error_log = "❌ UNAUTHORIZED - Username: " . ($_SESSION['username'] ?? 'NULL') . ", Role: " . ($_SESSION['role'] ?? 'NULL') . "\n";
    file_put_contents(__DIR__ . '/debug_telegram.log', $error_log, FILE_APPEND);
    echo json_encode(["status" => "error", "message" => "Unauthorized - Silakan login terlebih dahulu"]);
    exit;
}

// ============================================
// FUNGSI PENDUKUNG
// ============================================

function getPengaturanJam($conn) {
    $pengaturan = [
        'jam_masuk' => '07:00:00',
        'jam_pulang' => '15:00:00',
        'toleransi_masuk' => 15,
        'toleransi_pulang' => 15,
        'status' => 'aktif'
    ];
    
    $checkTable = mysqli_query($conn, "SHOW TABLES LIKE 'pengaturan_jam'");
    if (mysqli_num_rows($checkTable) > 0) {
        $query = "SELECT * FROM pengaturan_jam WHERE id = 1";
        $result = mysqli_query($conn, $query);
        if ($result && mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $pengaturan = [
                'jam_masuk' => $row['jam_masuk'],
                'jam_pulang' => $row['jam_pulang'],
                'toleransi_masuk' => (int)$row['toleransi_masuk'],
                'toleransi_pulang' => (int)$row['toleransi_pulang'],
                'status' => $row['status']
            ];
        }
    }
    
    return $pengaturan;
}

function cekStatusKehadiran($jam_absen, $jam_harus, $toleransi) {
    $jam_absen_time = strtotime($jam_absen);
    $jam_harus_time = strtotime($jam_harus);
    $jam_toleransi = strtotime("+{$toleransi} minutes", $jam_harus_time);
    
    if ($jam_absen_time <= $jam_toleransi) {
        return "Tepat Waktu";
    } else {
        $selisih_menit = round(($jam_absen_time - $jam_toleransi) / 60);
        return "Terlambat {$selisih_menit} menit";
    }
}

function cekBatasAbsensi($jam_masuk_terakhir, $current_time = null) {
    if ($current_time === null) {
        $current_time = time();
    }
    
    $jam_masuk_time = strtotime($jam_masuk_terakhir);
    $selisih_menit = ($current_time - $jam_masuk_time) / 60;
    
    if ($selisih_menit < 3) {
        return [
            'status' => false,
            'menit_tunggu' => ceil(3 - $selisih_menit)
        ];
    }
    
    return ['status' => true, 'menit_tunggu' => 0];
}

function getFotoProfil($conn, $nisn = null, $nip = null) {
    if ($nisn) {
        $checkFotoColumn = mysqli_query($conn, "SHOW COLUMNS FROM siswa LIKE 'foto'");
        if ($checkFotoColumn && mysqli_num_rows($checkFotoColumn) > 0) {
            $query = "SELECT foto FROM siswa WHERE nisn = '$nisn'";
            $result = mysqli_query($conn, $query);
            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                if (!empty($row['foto'])) {
                    return $row['foto'];
                }
            }
        }
    }
    
    if ($nip) {
        $checkFotoColumn = mysqli_query($conn, "SHOW COLUMNS FROM guru LIKE 'foto'");
        if ($checkFotoColumn && mysqli_num_rows($checkFotoColumn) > 0) {
            $query = "SELECT foto FROM guru WHERE nip = '$nip'";
            $result = mysqli_query($conn, $query);
            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                if (!empty($row['foto'])) {
                    return $row['foto'];
                }
            }
        }
    }
    
    return 'assets/images/default-avatar.png';
}

// ============================================
// FUNGSI KIRIM NOTIFIKASI - DENGAN DEBUG DETAIL
// ============================================

function kirimNotifikasi($conn, $no_wa, $pesan, $telegram_id = null) {
    $results = [];
    
    // DEBUG DETAIL
    $debug = "=== KIRIM NOTIFIKASI ===\n";
    $debug .= "No WA: " . ($no_wa ?: 'KOSONG') . "\n";
    $debug .= "Telegram ID: " . ($telegram_id ?: 'KOSONG') . "\n";
    $debug .= "Pesan length: " . strlen($pesan) . "\n";
    file_put_contents(__DIR__ . '/debug_telegram.log', $debug, FILE_APPEND);
    
    // 1. Kirim WA
    if (!empty($no_wa) && $no_wa !== '0' && $no_wa !== '62') {
        $wa_result = kirimWA($conn, $no_wa, $pesan);
        $results[] = $wa_result;
        file_put_contents(__DIR__ . '/debug_telegram.log', "WA Result: " . $wa_result . "\n", FILE_APPEND);
    } else {
        $results[] = "⚠️ Nomor WA tidak tersedia";
        file_put_contents(__DIR__ . '/debug_telegram.log', "WA: Nomor tidak tersedia\n", FILE_APPEND);
    }
    
    // 2. Kirim Telegram ke Admin
    file_put_contents(__DIR__ . '/debug_telegram.log', "Mengirim Telegram ke Admin (ID: " . TELEGRAM_CHAT_ID . ")\n", FILE_APPEND);
    $admin_result = kirimTelegram($pesan);
    $results[] = "Admin: " . $admin_result;
    file_put_contents(__DIR__ . '/debug_telegram.log', "Telegram Admin Result: " . $admin_result . "\n", FILE_APPEND);
    
    // 3. Kirim Telegram ke Siswa
    if (!empty($telegram_id) && preg_match('/^[0-9]+$/', $telegram_id)) {
        file_put_contents(__DIR__ . '/debug_telegram.log', "Mengirim Telegram ke Siswa (ID: $telegram_id)\n", FILE_APPEND);
        $siswa_result = kirimTelegram($pesan, $telegram_id);
        $results[] = "Siswa: " . $siswa_result;
        file_put_contents(__DIR__ . '/debug_telegram.log', "Telegram Siswa Result: " . $siswa_result . "\n", FILE_APPEND);
    } else {
        $results[] = "Siswa: ⚠️ Telegram ID tidak tersedia";
        file_put_contents(__DIR__ . '/debug_telegram.log', "Telegram Siswa: ID tidak tersedia (Value: '" . ($telegram_id ?: 'NULL') . "')\n", FILE_APPEND);
    }
    
    $final_result = implode(" | ", $results);
    file_put_contents(__DIR__ . '/debug_telegram.log', "FINAL RESULT: " . $final_result . "\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/debug_telegram.log', "=== SELESAI ===\n\n", FILE_APPEND);
    
    return $final_result;
}

// ============================================
// FUNGSI KIRIM WA
// ============================================

function kirimWA($conn, $no_wa, $pesan) {
    if (empty($no_wa) || $no_wa === '0' || $no_wa === '62') {
        return "⚠️ Nomor WA tidak tersedia";
    }

    $no_wa = preg_replace('/[^0-9]/', '', $no_wa);
    if (strlen($no_wa) < 10) {
        return "⚠️ Nomor WA tidak valid";
    }

    if (substr($no_wa, 0, 1) === "0") {
        $no_wa = "+62" . substr($no_wa, 1);
    } elseif (substr($no_wa, 0, 2) !== "62") {
        $no_wa = "+62" . $no_wa;
    } elseif (substr($no_wa, 0, 3) !== "+62") {
        $no_wa = "+" . $no_wa;
    }

    $secretKey = "";
    $qKey = mysqli_query($conn, "SELECT key_wa_sidobe FROM profil_sekolah LIMIT 1");
    if ($qKey && mysqli_num_rows($qKey) > 0) {
        $rowKey = mysqli_fetch_assoc($qKey);
        $secretKey = $rowKey['key_wa_sidobe'] ?? "";
    }

    if (empty($secretKey)) {
        return "⚠️ Secret key WA belum diset";
    }

    $data = ['phone' => $no_wa, 'message' => $pesan];
    $ch = curl_init('https://api.sidobe.com/wa/v1/send-message');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-Secret-Key: ' . $secretKey
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error_msg = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        error_log("Gagal kirim WA: " . $error_msg);
        return "⚠️ Gagal terhubung ke server WA: " . $error_msg;
    }

    $res = json_decode($response, true);
    if ($res && isset($res['is_success']) && $res['is_success']) {
        return "📲 WA berhasil dikirim";
    } else {
        $error_info = isset($res['message']) ? $res['message'] : 'Tidak ada info error';
        error_log("Gagal kirim WA. HTTP Code: $httpCode, Response: " . $response);
        return "⚠️ Gagal kirim WA. Error: $error_info";
    }
}

// ============================================
// PROSES UTAMA
// ============================================

try {
    if (isset($_GET['code'])) {
        $kode = mysqli_real_escape_string($conn, $_GET['code']);
        
        $siswa_query = mysqli_query($conn, "SELECT nisn FROM siswa WHERE nisn = '$kode' AND status = 'aktif' LIMIT 1");
        $guru_query = mysqli_query($conn, "SELECT nip FROM guru WHERE nip = '$kode' AND status = 'aktif' LIMIT 1");
        
        if ($siswa_query && mysqli_num_rows($siswa_query) > 0) {
            $_GET['nisn'] = $kode;
            file_put_contents(__DIR__ . '/debug_telegram.log', "✅ Ditemukan sebagai SISWA: NISN=$kode\n", FILE_APPEND);
        } elseif ($guru_query && mysqli_num_rows($guru_query) > 0) {
            $_GET['nip'] = $kode;
            file_put_contents(__DIR__ . '/debug_telegram.log', "✅ Ditemukan sebagai GURU: NIP=$kode\n", FILE_APPEND);
        } else {
            throw new Exception("❌ QR Code tidak valid atau data tidak ditemukan");
        }
    }

    if (!isset($_GET['nisn']) && !isset($_GET['nip'])) {
        throw new Exception("QR Code tidak ditemukan");
    }

    $tanggal = date("Y-m-d");
    $jam     = date("H:i:s");
    $operator = $_SESSION['username'];

    file_put_contents(__DIR__ . '/debug_telegram.log', "Tanggal: $tanggal, Jam: $jam, Operator: $operator\n", FILE_APPEND);

    if (isset($_GET['nisn'])) {
        file_put_contents(__DIR__ . '/debug_telegram.log', "▶️ Memproses absensi siswa...\n", FILE_APPEND);
        processSiswaAbsensi($conn, $_GET['nisn'], $tanggal, $jam, $operator);
    }

    if (isset($_GET['nip'])) {
        file_put_contents(__DIR__ . '/debug_telegram.log', "▶️ Memproses absensi guru...\n", FILE_APPEND);
        processGuruAbsensi($conn, $_GET['nip'], $tanggal, $jam, $operator);
    }

} catch (Exception $e) {
    file_put_contents(__DIR__ . '/debug_telegram.log', "❌ ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    exit;
}

// ============================================
// PROSES ABSENSI SISWA
// ============================================

function processSiswaAbsensi($conn, $nisn, $tanggal, $jam, $operator) {
    $nisn = mysqli_real_escape_string($conn, $nisn);
    $sql = "SELECT id, nama, kelas, no_wa, telegram_id FROM siswa WHERE nisn='$nisn' AND status='aktif' LIMIT 1";
    $res = mysqli_query($conn, $sql);

    if (!$res) {
        throw new Exception("❌ Error query siswa: " . mysqli_error($conn));
    }

    if (mysqli_num_rows($res) == 0) {
        throw new Exception("❌ Siswa dengan NISN $nisn tidak ditemukan");
    }

    $s = mysqli_fetch_assoc($res);
    $siswa_id = $s['id'];
    $nama     = $s['nama'];
    $kelas    = $s['kelas'];
    $no_wa    = $s['no_wa'] ?? '';
    $telegram_id = $s['telegram_id'] ?? '';

    // DEBUG - Data siswa
    file_put_contents(__DIR__ . '/debug_telegram.log', "📋 Data Siswa:\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/debug_telegram.log', "  ID: $siswa_id\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/debug_telegram.log', "  Nama: $nama\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/debug_telegram.log', "  Kelas: $kelas\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/debug_telegram.log', "  No WA: " . ($no_wa ?: 'KOSONG') . "\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/debug_telegram.log', "  Telegram ID: " . ($telegram_id ?: 'KOSONG') . "\n", FILE_APPEND);

    $foto_siswa = getFotoProfil($conn, $nisn, null);

    if ($_SESSION['role'] === 'wali_kelas') {
        $kelas_diampu = $_SESSION['kelas_diampu'] ?? '';
        if ($kelas !== $kelas_diampu) {
            throw new Exception("❌ Siswa $nama ($kelas) bukan dari kelas yang Anda ampu ($kelas_diampu)");
        }
    }

    $pengaturan = getPengaturanJam($conn);
    
    $check_jam_pulang = mysqli_query($conn, "SHOW COLUMNS FROM absensi LIKE 'jam_pulang'");
    $jam_pulang_exists = ($check_jam_pulang && mysqli_num_rows($check_jam_pulang) > 0);
    $check_wa_terkirim = mysqli_query($conn, "SHOW COLUMNS FROM absensi LIKE 'wa_terkirim'");
    $wa_terkirim_exists = ($check_wa_terkirim && mysqli_num_rows($check_wa_terkirim) > 0);

    $cek = mysqli_query($conn, "SELECT * FROM absensi WHERE siswa_id='$siswa_id' AND tanggal='$tanggal' LIMIT 1");

    if (!$cek) {
        throw new Exception("❌ Error query absensi: " . mysqli_error($conn));
    }

    if (mysqli_num_rows($cek) == 0) {
        // ABSEN MASUK
        $status_kehadiran = "Tepat Waktu";
        $keterangan = "";
        
        if ($pengaturan['status'] === 'aktif') {
            $status_kehadiran = cekStatusKehadiran($jam, $pengaturan['jam_masuk'], $pengaturan['toleransi_masuk']);
            $keterangan = strpos($status_kehadiran, "Terlambat") !== false ? "Status: Terlambat" : "Status: Tepat Waktu";
        }

        if ($wa_terkirim_exists) {
            $insert = mysqli_query($conn, "INSERT INTO absensi (siswa_id, tanggal, jam, status, keterangan, wa_terkirim) VALUES ('$siswa_id','$tanggal','$jam','H','$keterangan',0)");
        } else {
            $insert = mysqli_query($conn, "INSERT INTO absensi (siswa_id, tanggal, jam, status, keterangan) VALUES ('$siswa_id','$tanggal','$jam','H','$keterangan')");
        }

        if (!$insert) {
            throw new Exception("❌ Gagal simpan absen siswa: " . mysqli_error($conn));
        }

        file_put_contents(__DIR__ . '/debug_telegram.log', "✅ Absensi masuk berhasil disimpan\n", FILE_APPEND);

        // KIRIM NOTIFIKASI
        $pesan = "🏫 NOTIFIKASI ABSENSI SISWA\n\n";
        $pesan .= "Nama: $nama\n";
        $pesan .= "Kelas: $kelas\n";
        $pesan .= "Status: HADIR\n";
        $pesan .= "Waktu: " . date("d-m-Y H:i:s") . "\n";
        $pesan .= "Keterangan: $status_kehadiran\n";
        $pesan .= "\nTerima kasih.";

        file_put_contents(__DIR__ . '/debug_telegram.log', "📨 Mengirim notifikasi...\n", FILE_APPEND);
        $notif_status = kirimNotifikasi($conn, $no_wa, $pesan, $telegram_id);

        if ($wa_terkirim_exists && strpos($notif_status, "WA berhasil") !== false) {
            mysqli_query($conn, "UPDATE absensi SET wa_terkirim=1 WHERE siswa_id='$siswa_id' AND tanggal='$tanggal'");
        }

        $operator_info = ($_SESSION['role'] === 'wali_kelas') ? " (Oleh Wali Kelas)" : "";
        
        $response = [
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi masuk.<br>Jam: $jam<br>Status: $status_kehadiran{$operator_info}<br>$notif_status",
            "nama" => $nama,
            "kelas" => $kelas,
            "jam" => date("H:i", strtotime($jam)),
            "foto" => $foto_siswa,
            "tipe" => "siswa",
            "status_kehadiran" => $status_kehadiran,
            "debug" => [
                "telegram_id" => $telegram_id,
                "no_wa" => $no_wa,
                "notif_status" => $notif_status
            ]
        ];
        
        file_put_contents(__DIR__ . '/debug_telegram.log', "📤 Response: " . json_encode($response) . "\n", FILE_APPEND);
        echo json_encode($response);
        exit;
    }

    $row = mysqli_fetch_assoc($cek);

    // ABSEN PULANG
    if (!$jam_pulang_exists || empty($row['jam_pulang'])) {
        $batas_cek = cekBatasAbsensi($row['jam']);
        if (!$batas_cek['status']) {
            echo json_encode([
                "status" => "warning", 
                "message" => "⏳ $nama sukses melakukan absensi, Tunggu waktu pulang untuk melakukan absensi pulang",
                "nama" => $nama,
                "kelas" => $kelas,
                "foto" => $foto_siswa,
                "tipe" => "siswa"
            ]);
            exit;
        }

        if (!$jam_pulang_exists) {
            mysqli_query($conn, "ALTER TABLE absensi ADD COLUMN jam_pulang TIME NULL AFTER jam");
            $jam_pulang_exists = true;
        }

        $update = mysqli_query($conn, "UPDATE absensi SET jam_pulang='$jam' WHERE id={$row['id']}");

        if (!$update) {
            throw new Exception("❌ Gagal update absen siswa");
        }

        $pesan = "🏫 NOTIFIKASI ABSENSI SISWA\n\n";
        $pesan .= "Nama: $nama\n";
        $pesan .= "Kelas: $kelas\n";
        $pesan .= "Status: PULANG\n";
        $pesan .= "Jam Masuk: " . date("H:i", strtotime($row['jam'])) . "\n";
        $pesan .= "Jam Pulang: " . date("H:i", strtotime($jam)) . "\n";
        $pesan .= "\nTerima kasih.";
        
        $notif_status = kirimNotifikasi($conn, $no_wa, $pesan, $telegram_id);

        $operator_info = ($_SESSION['role'] === 'wali_kelas') ? " (Oleh Wali Kelas)" : "";

        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi pulang<br>Jam masuk: " . date("H:i", strtotime($row['jam'])) . "<br>Jam pulang: " . date("H:i", strtotime($jam)) . "{$operator_info}<br>$notif_status",
            "nama" => $nama,
            "kelas" => $kelas,
            "jam_masuk" => date("H:i", strtotime($row['jam'])),
            "jam_pulang" => date("H:i", strtotime($jam)),
            "foto" => $foto_siswa,
            "tipe" => "siswa"
        ]);
        exit;
    }

    echo json_encode([
        "status" => "warning", 
        "message" => "ℹ️ $nama sudah absen pulang hari ini.<br>Jam hadir: " . date("H:i", strtotime($row['jam'])) . "<br>Jam pulang: " . date("H:i", strtotime($row['jam_pulang'])),
        "nama" => $nama,
        "kelas" => $kelas,
        "foto" => $foto_siswa,
        "tipe" => "siswa"
    ]);
    exit;
}

// ============================================
// PROSES ABSENSI GURU
// ============================================

function processGuruAbsensi($conn, $nip, $tanggal, $jam, $operator) {
    $nip = mysqli_real_escape_string($conn, $nip);
    $q_guru = mysqli_query($conn, "SELECT id, nama, no_wa FROM guru WHERE nip='$nip' AND status='aktif' LIMIT 1");
    
    if (!$q_guru) {
        throw new Exception("❌ Error query guru: " . mysqli_error($conn));
    }

    if (mysqli_num_rows($q_guru) == 0) {
        throw new Exception("❌ Guru dengan NIP $nip tidak ditemukan");
    }

    $g = mysqli_fetch_assoc($q_guru);
    $guru_id = $g['id'];
    $nama    = $g['nama'];
    $no_wa   = $g['no_wa'] ?? '';

    $foto_guru = getFotoProfil($conn, null, $nip);

    $check_table = mysqli_query($conn, "SHOW TABLES LIKE 'absensi_guru'");
    if (mysqli_num_rows($check_table) == 0) {
        $create_table = mysqli_query($conn, "CREATE TABLE absensi_guru (
            id INT AUTO_INCREMENT PRIMARY KEY,
            guru_id INT NOT NULL,
            tanggal DATE NOT NULL,
            jam_masuk TIME NOT NULL,
            jam_pulang TIME NULL,
            status ENUM('H','I','S','A') DEFAULT 'H',
            operator VARCHAR(255) NOT NULL,
            keterangan VARCHAR(255) NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        if (!$create_table) {
            throw new Exception("❌ Gagal membuat tabel absensi_guru: " . mysqli_error($conn));
        }
    }

    $cek = mysqli_query($conn, "SELECT * FROM absensi_guru WHERE guru_id='$guru_id' AND tanggal='$tanggal' LIMIT 1");
    
    if (!$cek) {
        throw new Exception("❌ Error query absensi_guru: " . mysqli_error($conn));
    }

    if (mysqli_num_rows($cek) == 0) {
        $pengaturan = getPengaturanJam($conn);
        
        $keterangan = "";
        if ($pengaturan['status'] === 'aktif') {
            $status_kehadiran = cekStatusKehadiran($jam, $pengaturan['jam_masuk'], $pengaturan['toleransi_masuk']);
            $keterangan = $status_kehadiran;
        } else {
            $keterangan = "Tepat Waktu";
        }
        
        $insert = mysqli_query($conn, "INSERT INTO absensi_guru (guru_id, tanggal, jam_masuk, operator, keterangan) VALUES ('$guru_id', '$tanggal', '$jam', '$operator', '$keterangan')");
        
        if (!$insert) {
            throw new Exception("❌ Gagal simpan absen guru: " . mysqli_error($conn));
        }

        $pesan = "👨‍🏫 NOTIFIKASI ABSENSI GURU\n\n";
        $pesan .= "Nama: $nama\n";
        $pesan .= "Status: HADIR\n";
        $pesan .= "Waktu: " . date("d-m-Y H:i:s") . "\n";
        $pesan .= "Keterangan: $keterangan\n";
        $pesan .= "\nTerima kasih.";
        
        $notif_status = kirimNotifikasi($conn, $no_wa, $pesan, null);
        
        $operator_info = ($_SESSION['role'] === 'wali_kelas') ? " (Oleh Wali Kelas)" : "";
        
        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi masuk.<br>Jam: $jam<br>Status: $keterangan{$operator_info}<br>$notif_status",
            "nama" => $nama,
            "jam" => date("H:i", strtotime($jam)),
            "foto" => $foto_guru,
            "tipe" => "guru",
            "status_kehadiran" => $keterangan
        ]);
        exit;
    }

    $row = mysqli_fetch_assoc($cek);
    if (empty($row['jam_pulang'])) {
        $batas_cek = cekBatasAbsensi($row['jam_masuk']);
        if (!$batas_cek['status']) {
            echo json_encode([
                "status" => "warning", 
                "message" => "⏳ $nama sukses melakukan absensi, Tunggu waktu pulang untuk melakukan absensi pulang",
                "nama" => $nama,
                "foto" => $foto_guru,
                "tipe" => "guru"
            ]);
            exit;
        }

        $update = mysqli_query($conn, "UPDATE absensi_guru SET jam_pulang='$jam' WHERE id={$row['id']}");
        
        if (!$update) {
            throw new Exception("❌ Gagal update absen guru");
        }

        $pesan = "👨‍🏫 NOTIFIKASI ABSENSI GURU\n\n";
        $pesan .= "Nama: $nama\n";
        $pesan .= "Status: PULANG\n";
        $pesan .= "Jam Masuk: " . date("H:i", strtotime($row['jam_masuk'])) . "\n";
        $pesan .= "Jam Pulang: " . date("H:i", strtotime($jam)) . "\n";
        $pesan .= "\nTerima kasih.";
        
        $notif_status = kirimNotifikasi($conn, $no_wa, $pesan, null);
        
        $operator_info = ($_SESSION['role'] === 'wali_kelas') ? " (Oleh Wali Kelas)" : "";
        
        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi pulang<br>Jam masuk: " . date("H:i", strtotime($row['jam_masuk'])) . "<br>Jam pulang: " . date("H:i", strtotime($jam)) . "{$operator_info}<br>$notif_status",
            "nama" => $nama,
            "jam_masuk" => date("H:i", strtotime($row['jam_masuk'])),
            "jam_pulang" => date("H:i", strtotime($jam)),
            "foto" => $foto_guru,
            "tipe" => "guru"
        ]);
        exit;
    }

    echo json_encode([
        "status" => "warning", 
        "message" => "ℹ️ Guru $nama sudah absen masuk & pulang hari ini.<br>Jam masuk: " . date("H:i", strtotime($row['jam_masuk'])) . "<br>Jam pulang: " . date("H:i", strtotime($row['jam_pulang'])),
        "nama" => $nama,
        "foto" => $foto_guru,
        "tipe" => "guru"
    ]);
    exit;
}
?>