<?php
// Mencegah karakter liar merusak format JSON
ob_start();

// ===== HEADER CORS =====
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

header('Content-Type: application/json; charset=utf-8');

include "koneksi.php";

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

if (!$koneksi) {
    ob_end_clean();
    echo json_encode(["status" => "error", "message" => "Gagal menyambung ke database."]);
    exit();
}

// Ambil payload JSON dari Flutter
$raw_data = file_get_contents("php://input");
$data = json_decode($raw_data, true);

$id = isset($data['id']) ? $data['id'] : (isset($_POST['id']) ? $_POST['id'] : '');
$status = isset($data['status']) ? $data['status'] : (isset($_POST['status']) ? $_POST['status'] : '');
$setujui_oleh_raw = isset($data['setujui_oleh']) ? $data['setujui_oleh'] : (isset($_POST['setujui_oleh']) ? $_POST['setujui_oleh'] : 'Admin');

$id = mysqli_real_escape_string($koneksi, trim($id));
$status = mysqli_real_escape_string($koneksi, trim($status));
$setujui_oleh = mysqli_real_escape_string($koneksi, trim($setujui_oleh_raw));

if (empty($id) || empty($status)) {
    ob_end_clean();
    echo json_encode(["status" => "error", "message" => "Data ID dan status wajib diisi."]);
    exit();
}

// 1. Ambil data cuti & fcm_token dari tabel KARYAWAN (Relasi via no_kartu)
// Jika relasinya pakai 'nik' atau 'id_karyawan', ubah k.no_kartu menjadi k.nik
$sql_check = "SELECT c.*, k.fcm_token 
              FROM cuti c 
              LEFT JOIN karyawan k ON c.no_kartu = k.no_kartu 
              WHERE c.id = '$id'";
$query_check = mysqli_query($koneksi, $sql_check);
$data_cuti = mysqli_fetch_assoc($query_check);

if (!$data_cuti) {
    ob_end_clean();
    echo json_encode(["status" => "error", "message" => "Data cuti tidak ditemukan."]);
    exit();
}

// 2. Update status di tabel cuti
$sql = "UPDATE cuti SET status = '$status', setujui_oleh = '$setujui_oleh' WHERE id = '$id'";
$query = mysqli_query($koneksi, $sql);

if ($query) {
    $user_fcm_token = isset($data_cuti['fcm_token']) ? $data_cuti['fcm_token'] : '';
    $fcm_info = "Token tidak ditemukan di tabel karyawan.";

    // 3. Kirim FCM jika Token Ditemukan
    if (!empty($user_fcm_token)) {
        $status_text = (strtolower($status) == 'approved' || strtolower($status) == 'disetujui') ? 'DISETUJUI' : 'DITOLAK';
        $title = "Status Pengajuan Cuti";
        $body = "Pengajuan cuti Anda telah $status_text oleh $setujui_oleh.";

        $fcm_info = sendFCMv1($user_fcm_token, $title, $body);
    }

    ob_end_clean();
    echo json_encode([
        "status" => "success", 
        "message" => "Status berhasil diperbarui oleh $setujui_oleh.",
        "fcm_status" => $fcm_info
    ]);
} else {
    ob_end_clean();
    echo json_encode(["status" => "error", "message" => mysqli_error($koneksi)]);
}


// ===== FUNGSI UNTUK KIRIM NOTIFIKASI FCM (HTTP v1) =====
// ===== FUNGSI UNTUK KIRIM NOTIFIKASI FCM (HTTP v1) =====
function sendFCMv1($target_token, $title, $body) {
    // Tambahkan ../ agar keluar dari adm_control_api dan masuk ke folder firebase
    $serviceAccountPath = dirname(__DIR__) . '/firebase/service-account.json'; 
    
    if (!file_exists($serviceAccountPath)) {
        return "File service-account.json tidak ditemukan di: " . $serviceAccountPath;
    }

    $serviceAccount = json_decode(file_get_contents($serviceAccountPath), true);
    if (!$serviceAccount || !isset($serviceAccount['project_id'])) {
        return "Isi service-account.json tidak valid/corrupt";
    }

    $projectId = $serviceAccount['project_id'];
    $accessToken = getGoogleAccessToken($serviceAccount);
    
    if (!$accessToken) {
        return "Gagal membuat Access Token Google (Cek OpenSSL)";
    }

    $url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";

    $payload = [
        'message' => [
            'token' => $target_token,
            'notification' => [
                'title' => $title,
                'body'  => $body
            ],
            'data' => [
                'type' => 'cuti_status_update'
            ]
        ]
    ];

    $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($payload));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return "FCM Response (" . $httpCode . "): " . $response;
}

// ===== HELPER JWT GOOGLE ACCESS TOKEN =====
function getGoogleAccessToken($serviceAccount) {
    if (!function_exists('openssl_sign')) return null;

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $now = time();
    $claims = json_encode([
        'iss' => $serviceAccount['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'exp' => $now + 3600,
        'iat' => $now
    ]);

    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlClaims = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($claims));

    $signatureInput = $base64UrlHeader . "." . $base64UrlClaims;
    
    $success = @openssl_sign($signatureInput, $signature, $serviceAccount['private_key'], 'SHA256');
    if (!$success) return null;

    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    $jwt = $signatureInput . "." . $base64UrlSignature;

    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));

    $exec = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($exec, true);
    return isset($res['access_token']) ? $res['access_token'] : null;
}
?>