<?php
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') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once '../config/database.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Validate required fields
    $required_fields = ['user_id', 'device_token'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    // Validate user_id
    if (!is_numeric($input['user_id']) || $input['user_id'] <= 0) {
        throw new Exception('Invalid user ID');
    }
    
    // Validate device token
    if (strlen($input['device_token']) < 10) {
        throw new Exception('Invalid device token format');
    }
    
    $pdo = getDBConnection();
    
    // Check if user exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->execute([$input['user_id']]);
    if (!$stmt->fetch()) {
        throw new Exception('User not found');
    }
    
    // Update device token
    $stmt = $pdo->prepare("UPDATE users SET device_token = ? WHERE id = ?");
    $result = $stmt->execute([$input['device_token'], $input['user_id']]);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Device token updated successfully',
            'user_id' => $input['user_id'],
            'device_token' => $input['device_token']
        ]);
    } else {
        throw new Exception('Failed to update device token');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?> 