<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Panggil autoload Composer untuk menggunakan Google\Client
require __DIR__ . '/../vendor/autoload.php';
use Google\Client;

$response = ["status" => "error", "message" => "Terjadi kesalahan internal pada server"];

try {
    include "../config/koneksi.php";

    if (!isset($koneksi) && isset($conn)) {
        $koneksi = $conn;
    }

    if (!$koneksi) {
        throw new Exception("Koneksi database gagal");
    }

    $no_kartu    = $_POST['no_kartu']    ?? '';
    $nama        = $_POST['nama']        ?? '';
    $jenis_cuti  = $_POST['jenis_cuti']  ?? '';
    $cuti_hari   = $_POST['cuti_hari']   ?? 0;
    $alasan      = $_POST['alasan']      ?? '';
    $tgl_mulai   = $_POST['tgl_mulai']   ?? null;
    $tgl_selesai = $_POST['tgl_selesai'] ?? $tgl_mulai;
    $tgl_input   = date('Y-m-d');

    // Sanitasi data input
    $no_kartu_clean    = mysqli_real_escape_string($koneksi, $no_kartu);
    $nama_clean        = mysqli_real_escape_string($koneksi, $nama);
    $jenis_cuti_clean  = mysqli_real_escape_string($koneksi, $jenis_cuti);
    $cuti_hari_clean   = mysqli_real_escape_string($koneksi, $cuti_hari);
    $alasan_clean      = mysqli_real_escape_string($koneksi, $alasan);
    $tgl_mulai_clean   = mysqli_real_escape_string($koneksi, $tgl_mulai);
    $tgl_selesai_clean = mysqli_real_escape_string($koneksi, $tgl_selesai);
    $tgl_input_clean   = mysqli_real_escape_string($koneksi, $tgl_input);

    // Eksekusi Query Insert ke tabel cuti
    $query = "INSERT INTO cuti (no_kartu, nama, jenis, cuti_hari, alasan, tgl_mulai, tgl_selesai, status, tgl_input, setujui_oleh) 
        VALUES ('$no_kartu_clean', '$nama_clean', '$jenis_cuti_clean', '$cuti_hari_clean', '$alasan_clean', '$tgl_mulai_clean', '$tgl_selesai_clean', 'Pending', '$tgl_input_clean', '-')";
    
    $insert = mysqli_query($koneksi, $query);

    if ($insert) {
        // ================= KIRIM NOTIFIKASI FCM KE ADMIN (LEVEL 1) =================
        $queryAdmin = "SELECT fcm_token FROM karyawan WHERE level = 1 AND fcm_token IS NOT NULL AND fcm_token != ''";
        $resultAdmin = mysqli_query($koneksi, $queryAdmin);

        $tokens = [];
        if ($resultAdmin) {
            while ($row = mysqli_fetch_assoc($resultAdmin)) {
                $tokens[] = $row['fcm_token'];
            }
        }

        if (!empty($tokens)) {
            $title = "📋 Pengajuan " . $jenis_cuti;
            $body  = "$nama mengajukan $jenis_cuti selama $cuti_hari hari. Alasan: $alasan";
            
            $accessToken = getAccessToken();
            $projectId   = "yapora-57d28";
            $url         = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

            if ($accessToken) {
                foreach ($tokens as $token) {
                    $message = [
                        "message" => [
                            "token" => $token,
                            "notification" => [
                                "title" => $title,
                                "body" => $body
                            ],
                            "data" => [
                                "type" => "cuti",
                                "no_kartu" => $no_kartu,
                                "status" => "done"
                            ],
                            "android" => [
                                "priority" => "high"
                            ]
                        ]
                    ];

                    $headers = [
                        "Authorization: Bearer " . $accessToken,
                        "Content-Type: application/json"
                    ];

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
                    
                    curl_exec($ch);
                    curl_close($ch);
                }
            }
        }

        $response = ["status" => "success", "message" => "Pengajuan cuti berhasil disimpan!"];
    } else {
        $response = ["status" => "error", "message" => mysqli_error($koneksi)];
    }
} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
}

echo json_encode($response);

// ================= FUNGSI GET ACCESS TOKEN MENGGUNAKAN GOOGLE CLIENT =================
function getAccessToken() {
    $client = new Client();
    
    $client->setAuthConfig(__DIR__ . '/../firebase/service-account.json');
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    
    $token = $client->fetchAccessTokenWithAssertion();

    if (isset($token['error'])) {
        return null;
    }

    return $token['access_token'] ?? null;
}
?>