<?php
/**
 * Notification Helper Utility
 * Handles saving notifications to DB and sending FCM push notifications.
 */

require_once __DIR__ . '/config.php';

/**
 * Add a notification to the database and optionally send a push notification.
 */
function addNotification($recipient_id, $title, $message, $type = 'info', $link = '', $recipient_type = 'customer') {
    $pdo = getDBConnection();

    try {
        // 1. Save to local database
        $stmt = $pdo->prepare("
            INSERT INTO notifications (user_id, recipient_type, title, message, type, link, is_read, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 0, NOW())
        ");
        $stmt->execute([$recipient_id, $recipient_type, $title, $message, $type, $link]);
        $notification_id = $pdo->lastInsertId();

        $notification_data = [
            'id' => $notification_id,
            'title' => $title,
            'message' => $message,
            'type' => $type,
            'link' => $link,
            'timestamp' => time() * 1000,
            'is_read' => 0
        ];

        // 2. Sync to Firebase Realtime Database (for real-time UI updates)
        syncToFirebaseRTDB($recipient_id, $recipient_type, $notification_data);

        // 3. Fetch recipient's FCM token
        $fcm_token = null;
        if ($recipient_type === 'admin') {
            $stmt = $pdo->prepare("SELECT fcm_token FROM admin_users WHERE id = ?");
        } else {
            $stmt = $pdo->prepare("SELECT fcm_token FROM users WHERE id = ?");
        }
        $stmt->execute([$recipient_id]);
        $fcm_token = $stmt->fetchColumn();

        // 4. Send FCM Push Notification if token exists
        if ($fcm_token) {
            sendPushNotification($fcm_token, $title, $message, [
                'notification_id' => $notification_id,
                'type' => $type,
                'link' => $link
            ]);
        }

        return $notification_id;
    } catch (Exception $e) {
        error_log("Failed to add notification: " . $e->getMessage());
        return false;
    }
}

/**
 * Send FCM Push Notification using Legacy API
 */
function sendPushNotification($fcm_token, $title, $message, $data = []) {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT key_value FROM settings WHERE key_name = 'fcm_server_key'");
    $stmt->execute();
    $server_key = $stmt->fetchColumn();

    if (empty($server_key)) {
        error_log("FCM Push Error: No server key found in settings.");
        return false;
    }

    $url = 'https://fcm.googleapis.com/fcm/send';

    $notification = [
        'title' => $title,
        'body' => $message,
        'sound' => 'default',
        'badge' => '1',
        'click_action' => $data['link'] ?? ''
    ];

    $payload = [
        'to' => $fcm_token,
        'notification' => $notification,
        'data' => $data,
        'priority' => 'high'
    ];

    $headers = [
        'Authorization: key=' . $server_key,
        '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_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $result = curl_exec($ch);
    $error = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200) {
        error_log("FCM Push Error: HTTP $http_code - Result: $result - CURL Error: $error");
        return false;
    }

    return true;
}

/**
 * Sync notification to Firebase Realtime Database via REST API
 */
function syncToFirebaseRTDB($recipient_id, $recipient_type, $data) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT key_value FROM settings WHERE key_name = 'firebase_database_url'");
        $stmt->execute();
        $db_url = rtrim($stmt->fetchColumn(), '/');

        if (empty($db_url)) {
            error_log("Firebase RTDB Sync Error: No database URL found in settings.");
            return false;
        }

        $firebase_url = "{$db_url}/notifications/{$recipient_type}_{$recipient_id}.json";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $firebase_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);

        $result = curl_exec($ch);
        $error = curl_error($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code >= 400) {
            error_log("Firebase RTDB Sync Error: HTTP $http_code - Result: $result - CURL Error: $error");
            return false;
        }

        return $result;
    } catch (Exception $e) {
        error_log("Firebase RTDB Sync Exception: " . $e->getMessage());
        return false;
    }
}

/**
 * Notify all admins
 */
function notifyAdmins($title, $message, $type = 'info', $link = '') {
    $pdo = getDBConnection();
    try {
        $stmt = $pdo->query("SELECT id FROM admin_users WHERE is_active = 1");
        $admins = $stmt->fetchAll(PDO::FETCH_COLUMN);

        foreach ($admins as $admin_id) {
            addNotification($admin_id, $title, $message, $type, $link, 'admin');
        }
    } catch (Exception $e) {
        error_log("Failed to notify admins: " . $e->getMessage());
    }
}
