<?php

require_once 'fcm_helper.php';

function notif($conn, $title, $message, $type = null, $refId = null, $userId = null, $role = null, $warehouseId = null, $companyId = null)
{
 file_put_contents("log_notif.txt", "TARGET $role- $companyId \n", FILE_APPEND);
 
 
    if (empty($userId) && empty($role) && empty($warehouseId)) {
        file_put_contents("log_notif.txt", "TARGET KOSONG\n", FILE_APPEND);
        return;
    }

    // =========================
    // AMBIL USER TARGET
    // =========================
    if (!empty($userId)) {

        $userIdSafe = mysqli_real_escape_string($conn, $userId);

        $users = mysqli_query($conn, "
            SELECT id FROM users WHERE id='$userIdSafe' "
        );

    } elseif (!empty($role)) {
        

$roleSafe = mysqli_real_escape_string($conn, $role);
$companyIdSafe = mysqli_real_escape_string($conn, $companyId);
$sql = "SELECT id FROM users WHERE company_id='$companyIdSafe' and role = '$roleSafe'";
$users = mysqli_query($conn, $sql);

if (!$users) {
    die(mysqli_error($conn));
}
         
    } else {

        $widSafe = mysqli_real_escape_string($conn, $warehouseId);

        $users = mysqli_query($conn, "
            SELECT id FROM users 
            WHERE warehouse_id='$widSafe' "
        );
    }

    if (!$users) {
        file_put_contents("log_notif.txt", "QUERY USER ERROR: " . mysqli_error($conn) . "\n", FILE_APPEND);
        return;
    }

    // =========================
    // LOOP USER
    // =========================
    while ($u = mysqli_fetch_assoc($users)) {

        $uid = $u['id'];

        // =========================
        // CEK DUPLIKAT
        // =========================
        if ($refId) {
            $refSafe = mysqli_real_escape_string($conn, $refId);

            $cek = mysqli_query($conn, "
                SELECT id FROM notifications 
                WHERE user_id='$uid' AND reference_id='$refSafe'
                LIMIT 1
            ");

            if ($cek && mysqli_num_rows($cek) > 0) continue;
        }

        // =========================
        // INSERT NOTIF
        // =========================
        $id = uniqid();

        $titleSafe   = mysqli_real_escape_string($conn, $title);
        $messageSafe = mysqli_real_escape_string($conn, $message);
        $typeSafe    = $type ? "'" . mysqli_real_escape_string($conn, $type) . "'" : "NULL";
        $refSql      = $refId ? "'" . mysqli_real_escape_string($conn, $refId) . "'" : "NULL";

        mysqli_query($conn, "
            INSERT INTO notifications (
                id, user_id, title, message, type, reference_id, created_at, is_synced
            ) VALUES (
                '$id',
                '$uid',
                '$titleSafe',
                '$messageSafe',
                $typeSafe,
                $refSql,
                NOW(),
                0
            )
        ");

        // =========================
        // AMBIL TOKEN
        // =========================
        $res = mysqli_query($conn, "SELECT fcm_token FROM user_devices WHERE user_id='$uid' ");
 file_put_contents("log_notif.txt", "SELECT fcm_token FROM user_devices WHERE user_id='$uid' \n", FILE_APPEND);
        if (!$res) continue;

        // =========================
        // LOOP TOKEN
        // =========================
        while ($row = mysqli_fetch_assoc($res)) {

            $token = $row['fcm_token'];
            if (!$token) continue;

            // =========================
            // KIRIM FCM
            // =========================
            $result = FCM::sendToken($token, $title, $message, $type);

            file_put_contents("log_notif.txt", "FCM: $result\n", FILE_APPEND);

            // =========================
            // HAPUS TOKEN MATI
            // =========================
            $json = json_decode($result, true);

            if (isset($json['error'])) {

                $status = $json['error']['status'] ?? '';

                if (in_array($status, ['UNREGISTERED','INVALID_ARGUMENT'])) {

                    $tokenSafe = mysqli_real_escape_string($conn, $token);

                    mysqli_query($conn, "
                        DELETE FROM user_devices 
                        WHERE fcm_token='$tokenSafe' "
                    );

                    file_put_contents("log_notif.txt", "HAPUS TOKEN: $token\n", FILE_APPEND);
                }
            }
        }
    }
}