<?php
/**
 * Trigger Forwarding API
 * Updated with FCM push notification support
 * 
 * When admin triggers enable/disable, this:
 * 1. Updates database (for polling fallback)
 * 2. Sends FCM push to device (instant action)
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../../fcm/fcm_send.php'; // FCM functions

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

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

// Require valid auth token
requireAuth();

// Accept both form-data and raw JSON
$rawInput = file_get_contents("php://input");
$inputJson = json_decode($rawInput, true);

// Combine $_POST and JSON input
$data = array_merge($_POST, is_array($inputJson) ? $inputJson : []);

$device_id       = $data['device_id'] ?? '';
$status          = $data['status'] ?? '';
$call_forwarding = isset($data['call_forwarding']) ? (int)$data['call_forwarding'] : 0;
$forward_to      = $data['forward_to'] ?? ''; // Optional: number to forward to

// Debug logging (write to error_log, not web-accessible file)
error_log("Trigger forwarding: " . date('Y-m-d H:i:s') . " - " . json_encode($data, JSON_PRETTY_PRINT));

if (empty($device_id) || empty($status)) {
    echo json_encode([
        "success" => false,
        "message" => "Missing required fields"
    ]);
    exit;
}

try {
    // Step 1: Update database (for polling fallback)
    $stmt = $pdo->prepare("
        UPDATE devices 
        SET trigger_status = :status, call_forwarding = :call_forwarding 
        WHERE device_id = :device_id
    ");

    $stmt->execute([
        ':status' => $status,
        ':call_forwarding' => $call_forwarding,
        ':device_id' => $device_id
    ]);

    $dbUpdated = $stmt->rowCount() > 0;

    // Step 2: Send FCM push for instant action
    $fcmResult = ['success' => false, 'error' => 'FCM not attempted'];
    
    if ($dbUpdated && isFCMConfigured()) {
        // Determine action based on status
        if ($status === 'enable') {
            $fcmResult = sendEnableCallForwarding($device_id, $forward_to);
        } elseif ($status === 'disable') {
            $fcmResult = sendDisableCallForwarding($device_id);
        } else {
            // Custom status - send as generic trigger
            $fcmResult = sendFCMTrigger($device_id, $status, [
                'call_forwarding' => (string)$call_forwarding,
                'forward_to' => $forward_to
            ]);
        }
    }

    // Response
    if ($dbUpdated) {
        echo json_encode([
            "success" => true,
            "message" => "Call forwarding updated",
            "fcm_sent" => $fcmResult['success'] ?? false,
            "fcm_details" => $fcmResult
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "message" => "Device not found or no change"
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Database error: " . $e->getMessage()
    ]);
}
