<?php
// file: rekam_absen_public.php
// VERSI PUBLIK - Copy dari rekam_absen_wa_api.php tanpa session

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

include "config.php";
// session_start(); // <-- DIHAPUS
date_default_timezone_set('Asia/Jakarta');

// Set header JSON pertama kali
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// HAPUS pengecekan session di sini!

// Log untuk debugging
error_log("Public API Dipanggil: " . date('Y-m-d H:i:s') . " - IP: " . $_SERVER['REMOTE_ADDR']);

// Fungsi untuk mendapatkan pengaturan jam absensi
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';
}

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;
        } elseif ($guru_query && mysqli_num_rows($guru_query) > 0) {
            $_GET['nip'] = $kode;
        } 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 = "Publik_Scan"; // <-- GANTI dari session jadi default

    if (isset($_GET['nisn'])) {
        processSiswaAbsensi($conn, $_GET['nisn'], $tanggal, $jam, $operator);
    }

    if (isset($_GET['nip'])) {
        processGuruAbsensi($conn, $_GET['nip'], $tanggal, $jam, $operator);
    }

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    exit;
}

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

    if (!$res || 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'] ?? '';

    $foto_siswa = getFotoProfil($conn, $nisn, null);
    $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 (mysqli_num_rows($cek) == 0) {
        $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) ? "Terlambat" : "Tepat Waktu";
        }

        $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));
        }

        $pesan = "Halo, Orang tua/wali dari $nama.\n\n";
        $pesan .= "Ananda ($kelas) telah HADIR pada " . date("d-m-Y H:i") . "\n";
        $pesan .= "Status: " . $status_kehadiran;
        
        $wa_status = kirimWA($conn, $no_wa, $pesan);

        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi masuk. Tunggu waktu pulang untuk melakukan absensi pulang\nJam: $jam\nStatus: $status_kehadiran\n$wa_status",
            "nama" => $nama,
            "kelas" => $kelas,
            "jam" => date("H:i", strtotime($jam)),
            "foto" => $foto_siswa,
            "tipe" => "siswa",
            "status_kehadiran" => $status_kehadiran
        ]);
        exit;
    }

    $row = mysqli_fetch_assoc($cek);

    if (!$jam_pulang_exists || empty($row['jam_pulang'])) {
        $batas_cek = cekBatasAbsensi($row['jam']);
        if (!$batas_cek['status']) {
            echo json_encode([
                "status" => "warning", 
                "message" => "⏳ Silakan tunggu {$batas_cek['menit_tunggu']} menit lagi untuk absen 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");
        }

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

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

        $pesan = "Halo, Orang tua/wali dari $nama.\n\n";
        $pesan .= "Ananda ($kelas) telah PULANG pada " . date("d-m-Y H:i") . "\n";
        $pesan .= "Jam Masuk: " . date("H:i", strtotime($row['jam'])) . "\n";
        $pesan .= "Jam Pulang: " . date("H:i", strtotime($jam));
        
        $wa_status = kirimWA($conn, $no_wa, $pesan);

        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi pulang\nJam masuk: " . date("H:i", strtotime($row['jam'])) . "\nJam pulang: " . date("H:i", strtotime($jam)) . "\n$wa_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 lengkap hari ini.\nJam hadir: " . date("H:i", strtotime($row['jam'])) . "\nJam pulang: " . date("H:i", strtotime($row['jam_pulang'])),
        "nama" => $nama,
        "kelas" => $kelas,
        "foto" => $foto_siswa,
        "tipe" => "siswa"
    ]);
    exit;
}

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 || 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) {
        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
        )");
    }

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

    if (mysqli_num_rows($cek) == 0) {
        $pengaturan = getPengaturanJam($conn);
        $keterangan = ($pengaturan['status'] === 'aktif') ? cekStatusKehadiran($jam, $pengaturan['jam_masuk'], $pengaturan['toleransi_masuk']) : "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 = "Halo, $nama.\n\n";
        $pesan .= "Anda telah melakukan ABSEN MASUK pada " . date("d-m-Y H:i") . "\n";
        $pesan .= "Status: " . $keterangan;
        $wa_status = kirimWA($conn, $no_wa, $pesan);
        
        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi masuk\nJam: $jam\nStatus: $keterangan\n$wa_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" => "⏳ Silakan tunggu {$batas_cek['menit_tunggu']} menit lagi untuk absen 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 = "Halo, $nama.\n\n";
        $pesan .= "Anda telah melakukan ABSEN PULANG pada " . date("d-m-Y H:i") . "\n";
        $pesan .= "Jam Masuk: " . date("H:i", strtotime($row['jam_masuk'])) . "\n";
        $pesan .= "Jam Pulang: " . date("H:i", strtotime($jam));
        $wa_status = kirimWA($conn, $no_wa, $pesan);
        
        echo json_encode([
            "status" => "success", 
            "message" => "✅ $nama sukses melakukan absensi pulang\nJam masuk: " . date("H:i", strtotime($row['jam_masuk'])) . "\nJam pulang: " . date("H:i", strtotime($jam)) . "\n$wa_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 lengkap hari ini.\nJam masuk: " . date("H:i", strtotime($row['jam_masuk'])) . "\nJam pulang: " . date("H:i", strtotime($row['jam_pulang'])),
        "nama" => $nama,
        "foto" => $foto_guru,
        "tipe" => "guru"
    ]);
    exit;
}

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

    $no_wa = preg_replace('/[^0-9]/', '', $no_wa);
    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_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response === false) {
        return "⚠️ Gagal kirim WA";
    }

    $res = json_decode($response, true);
    if ($res && isset($res['is_success']) && $res['is_success']) {
        return "📲 WA berhasil dikirim";
    }
    return "⚠️ Gagal kirim WA";
}
?>