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

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

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

// Hak akses
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru', 'siswa'])) {
    echo json_encode(["status" => "error", "message" => "Unauthorized"]);
    exit;
}

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

try {
    // Deteksi otomatis berdasarkan parameter
    if (isset($_GET['code'])) {
        $kode = mysqli_real_escape_string($conn, $_GET['code']);
        
        // Cek apakah ini NISN atau NIP
        $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 = $_SESSION['username'];

    /* ===================================================
       CEK SISWA
    =================================================== */
    if (isset($_GET['nisn'])) {
        processSiswaAbsensi($conn, $_GET['nisn'], $tanggal, $jam);
    }

    /* ===================================================
       CEK GURU
    =================================================== */
    if (isset($_GET['nip'])) {
        processGuruAbsensi($conn, $_GET['nip'], $tanggal, $jam, $operator);
    }

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

/* ===================================================
   FUNGSI PROSES ABSENSI SISWA
=================================================== */
function processSiswaAbsensi($conn, $nisn, $tanggal, $jam) {
    $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) {
        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'] ?? '';

    // cek jam_pulang & wa_terkirim
    $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);

    // ambil absensi hari ini
    $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
        if ($wa_terkirim_exists) {
            $insert = mysqli_query($conn, "INSERT INTO absensi (siswa_id, tanggal, jam, status, wa_terkirim) VALUES ('$siswa_id','$tanggal','$jam','H',0)");
        } else {
            $insert = mysqli_query($conn, "INSERT INTO absensi (siswa_id, tanggal, jam, status) VALUES ('$siswa_id','$tanggal','$jam','H')");
        }

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

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

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

        echo json_encode(["status" => "success", "message" => "✅ Absensi masuk siswa: $nama ($kelas) jam $jam<br>$wa_status"]);
        exit;
    }

    $row = mysqli_fetch_assoc($cek);

    // ABSEN PULANG
    if (!$jam_pulang_exists || empty($row['jam_pulang'])) {
        $jam_masuk = strtotime($row['jam']);
        $jam_sekarang = time();
        $selisih_menit = ($jam_sekarang - $jam_masuk) / 60;
        
        if ($selisih_menit < 3) {
            $menit_tunggu = ceil(3 - $selisih_menit);
            echo json_encode(["status" => "warning", "message" => "⏳ Tunggu $menit_tunggu menit lagi sebelum absen pulang."]);
            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 = "Halo, Orang tua/wali dari $nama.\n\nAnanda ($kelas) telah PULANG pada " . date("d-m-Y H:i");
        $wa_status = kirimWA($conn, $no_wa, $pesan);

        echo json_encode(["status" => "success", "message" => "✅ Absensi pulang siswa: $nama<br>Jam hadir: {$row['jam']}<br>Jam pulang: $jam<br>$wa_status"]);
        exit;
    }

    echo json_encode(["status" => "warning", "message" => "ℹ️ $nama sudah absen pulang.<br>Jam hadir: {$row['jam']}<br>Jam pulang: {$row['jam_pulang']}"]);
    exit;
}

/* ===================================================
   FUNGSI 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'] ?? '';

    // Pastikan tabel absensi_guru ada
    $check_table = mysqli_query($conn, "SHOW TABLES LIKE 'absensi_guru'");
    if (!$check_table) {
        throw new Exception("❌ Error checking table: " . mysqli_error($conn));
    }

    if (mysqli_num_rows($check_table) == 0) {
        // Buat tabel absensi_guru jika belum ada
        $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('hadir', 'terlambat', 'tidak_hadir') DEFAULT 'hadir',
            operator VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");

        if (!$create_table) {
            throw new Exception("❌ Gagal membuat tabel absensi_guru: " . mysqli_error($conn));
        }
    } else {
        // Periksa apakah kolom operator sudah ada
        $check_operator_column = mysqli_query($conn, "SHOW COLUMNS FROM absensi_guru LIKE 'operator'");
        if (!$check_operator_column || mysqli_num_rows($check_operator_column) == 0) {
            $alter_table = mysqli_query($conn, "ALTER TABLE absensi_guru ADD COLUMN operator VARCHAR(255) NOT NULL AFTER status");
            if (!$alter_table) {
                throw new Exception("❌ Gagal menambahkan kolom operator: " . 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) {
        // ABSEN MASUK GURU
        $insert = mysqli_query($conn, "INSERT INTO absensi_guru (guru_id, tanggal, jam_masuk, operator) VALUES ('$guru_id', '$tanggal', '$jam', '$operator')");
        
        if (!$insert) {
            throw new Exception("❌ Gagal simpan absen guru: " . mysqli_error($conn));
        }

        // Kirim notifikasi WA ke guru
        $pesan = "Halo, $nama.\n\nAnda telah melakukan ABSEN MASUK pada " . date("d-m-Y H:i");
        $wa_status = kirimWA($conn, $no_wa, $pesan);
        
        echo json_encode(["status" => "success", "message" => "✅ Absensi masuk guru: $nama jam $jam<br>$wa_status"]);
        exit;
    }

    $row = mysqli_fetch_assoc($cek);
    if (empty($row['jam_pulang'])) {
        $jam_masuk = strtotime($row['jam_masuk']);
        $jam_sekarang = time();
        $selisih_menit = ($jam_sekarang - $jam_masuk) / 60;
        
        if ($selisih_menit < 3) {
            $menit_tunggu = ceil(3 - $selisih_menit);
            echo json_encode(["status" => "warning", "message" => "⏳ Tunggu $menit_tunggu menit lagi sebelum absen pulang."]);
            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");
        }

        // Kirim notifikasi WA ke guru
        $pesan = "Halo, $nama.\n\nAnda telah melakukan ABSEN PULANG pada " . date("d-m-Y H:i");
        $wa_status = kirimWA($conn, $no_wa, $pesan);
        
        echo json_encode(["status" => "success", "message" => "✅ Absensi pulang guru: $nama jam $jam<br>$wa_status"]);
        exit;
    }

    echo json_encode(["status" => "warning", "message" => "ℹ️ Guru $nama sudah absen masuk & pulang hari ini"]);
    exit;
}

/* ===================================================
   FUNGSI KIRIM WA - DIPERBAIKI UNTUK SSL
=================================================== */
function kirimWA($conn, $no_wa, $pesan) {
    // Jika nomor WA kosong, kembalikan 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";
    }

    // Format nomor 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;
    }

    // Ambil secret key
    $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";
    }

    // Kirim WA dengan penanganan SSL yang lebih baik
    $data = ['phone' => $no_wa, 'message' => $pesan];
    $max_retries = 2;
    $retry_count = 0;
    $response = false;
    
    do {
        $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);
        
        // PENANGANAN SSL YANG DIPERBAIKI
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Nonaktifkan verifikasi SSL (sementara)
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);     // Nonaktifkan verifikasi host SSL
        
        // Alternatif: Gunakan certificate bundle dari sistem jika tersedia
        if (file_exists('cacert.pem')) {
            curl_setopt($ch, CURLOPT_CAINFO, 'cacert.pem');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error_msg = curl_error($ch);
        curl_close($ch);
        
        if ($response !== false) {
            break;
        }
        
        $retry_count++;
        if ($retry_count < $max_retries) {
            usleep(500000);
        }
    } while ($retry_count < $max_retries);

    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 ke " . substr($no_wa, 0, 6) . "****";
    } 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";
    }
}
?>