<?php
/**
 * FCM Test Endpoint
 * Use this to test if FCM is working correctly
 * 
 * GET: Check FCM configuration status
 * POST: Send test push to a device
 */

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

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

require_once __DIR__ . '/FCMHelper.php';
require_once __DIR__ . '/../adminapi/includes/db.php';

define('FCM_SERVICE_ACCOUNT_PATH', __DIR__ . '/firebase-service-account.json');

// GET: Check configuration status
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $status = [
        'fcm_configured' => false,
        'service_account_exists' => file_exists(FCM_SERVICE_ACCOUNT_PATH),
        'project_id' => null,
        'devices_with_fcm_token' => 0,
        'devices_without_fcm_token' => 0
    ];
    
    if ($status['service_account_exists']) {
        try {
            $fcm = new FCMHelper(FCM_SERVICE_ACCOUNT_PATH);
            $status['fcm_configured'] = true;
            $status['project_id'] = $fcm->getProjectId();
        } catch (Exception $e) {
            $status['error'] = $e->getMessage();
        }
    }
    
    // Count devices
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as total, SUM(CASE WHEN fcm_token IS NOT NULL AND fcm_token != '' THEN 1 ELSE 0 END) as with_token FROM devices");
        $counts = $stmt->fetch(PDO::FETCH_ASSOC);
        $status['devices_with_fcm_token'] = (int)$counts['with_token'];
        $status['devices_without_fcm_token'] = (int)$counts['total'] - (int)$counts['with_token'];
    } catch (Exception $e) {
        $status['db_error'] = $e->getMessage();
    }
    
    echo json_encode($status, JSON_PRETTY_PRINT);
    exit;
}

// POST: Send test push
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $device_id = $data['device_id'] ?? '';
    $message = $data['message'] ?? 'Test push from server';
    
    if (empty($device_id)) {
        echo json_encode(['success' => false, 'error' => 'Missing device_id']);
        exit;
    }
    
    if (!file_exists(FCM_SERVICE_ACCOUNT_PATH)) {
        echo json_encode(['success' => false, 'error' => 'FCM not configured - service account file missing']);
        exit;
    }
    
    try {
        // Get FCM token
        $stmt = $pdo->prepare("SELECT fcm_token FROM devices WHERE device_id = ?");
        $stmt->execute([$device_id]);
        $device = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$device) {
            echo json_encode(['success' => false, 'error' => 'Device not found']);
            exit;
        }
        
        if (empty($device['fcm_token'])) {
            echo json_encode(['success' => false, 'error' => 'Device has no FCM token - app needs to register']);
            exit;
        }
        
        // Send test push
        $fcm = new FCMHelper(FCM_SERVICE_ACCOUNT_PATH);
        $result = $fcm->sendDataMessage($device['fcm_token'], [
            'action' => 'test',
            'message' => $message,
            'timestamp' => (string)time()
        ]);
        
        echo json_encode([
            'success' => $result['success'],
            'device_id' => $device_id,
            'fcm_result' => $result
        ], JSON_PRETTY_PRINT);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

echo json_encode(['error' => 'Invalid request method']);
