<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include 'conexion.php';
include 'notification.php';

try {
    // Cek koneksi
    if ($connect->connect_error) {
        http_response_code(500);
        echo json_encode(['message' => 'Koneksi ke database gagal: ' . $connect->connect_error]);
        exit;
    }

    // Pastikan data dikirimkan menggunakan metode POST
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Data hardcoded untuk testing
        $title = "Promosi";
        $message = "Promosi Terbaru";
        $type = "promotion";
        $username = "Januar";

        // Insert notifikasi ke database
        $sql = "INSERT INTO notifications (title, message, type, username) VALUES (?, ?, ?, ?)";
        $stmt = $connect->prepare($sql);
        $stmt->bind_param("ssss", $title, $message, $type, $username);

        if (!$stmt->execute()) {
            throw new Exception("Gagal menambahkan notification: " . $stmt->error);
        }

        // Ambil semua token user terkait
        $tokens_sql = "SELECT token FROM user_tokens WHERE is_active = 1 AND username = ?";
        $tokens_stmt = $connect->prepare($tokens_sql);
        $tokens_stmt->bind_param("s", $username);
        $tokens_stmt->execute();
        $tokens_result = $tokens_stmt->get_result();

        $tokens = [];
        while ($row = $tokens_result->fetch_assoc()) {
            $tokens[] = $row['token'];
        }

        if (empty($tokens)) {
            throw new Exception('Tidak ada token FCM aktif untuk pengguna tersebut.');
        }

        // Ambil ID notifikasi terakhir
        $id_sql = "SELECT id FROM notifications ORDER BY id DESC LIMIT 1";
        $id_stmt = $connect->prepare($id_sql);
        $id_stmt->execute();
        $id_result = $id_stmt->get_result();
        $id_row = $id_result->fetch_assoc();

        if (!$id_row) {
            throw new Exception('ID notifikasi tidak ditemukan.');
        }

        $notification_id = $id_row['id'];

        // Kirim notifikasi FCM
        $fcm_response = sendFCMPromoNotification($tokens, $notification_id);

        if (!$fcm_response) {
            throw new Exception('Gagal mengirim notifikasi FCM.');
        }

        // Berhasil
        http_response_code(200);
        echo json_encode(['message' => 'Notifikasi berhasil dikirim']);
    } else {
        http_response_code(405);
        echo json_encode(['message' => 'Metode tidak diizinkan']);
    }
} catch (Exception $e) {
    // Tangkap semua error
    http_response_code(500);
    echo json_encode(['error' => true, 'message' => $e->getMessage()]);
} finally {
    // Tutup koneksi
    $connect->close();
}
