<?php
header('Content-Type: application/json');
require_once '../includes/db.php';

$data = json_decode(file_get_contents('php://input'), true);

// Debug logging
file_put_contents('fcm_log.txt', date('[Y-m-d H:i:s] ') . json_encode($data) . PHP_EOL, FILE_APPEND);

if (!isset($data['phone']) || !isset($data['token'])) {
    echo json_encode(['success' => false, 'error' => 'Missing phone or token']);
    exit;
}

try {
    // Insert or update token, always mark as valid when registering
    $stmt = $pdo->prepare("
        INSERT INTO fcm_tokens (phone, token, is_valid, updated_at) 
        VALUES (?, ?, 1, NOW()) 
        ON DUPLICATE KEY UPDATE 
            token = VALUES(token), 
            is_valid = 1, 
            updated_at = NOW()
    ");
    
    if ($stmt->execute([$data['phone'], $data['token']])) {
        echo json_encode(['success' => true]);
    } else {
        $errorInfo = $stmt->errorInfo();
        file_put_contents('fcm_log.txt', date('[Y-m-d H:i:s] ') . "EXECUTION ERROR: " . json_encode($errorInfo) . PHP_EOL, FILE_APPEND);
        echo json_encode(['success' => false, 'error' => 'Execution failed']);
    }
} catch (PDOException $e) {
    file_put_contents('fcm_log.txt', date('[Y-m-d H:i:s] ') . "DB ERROR: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>
