<?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', 'name'];
    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 name
    if (strlen(trim($input['name'])) < 2) {
        throw new Exception('Name must be at least 2 characters long');
    }
    
    // Validate city (make it optional)
    if (!empty($input['city']) && strlen(trim($input['city'])) < 2) {
        throw new Exception('City must be at least 2 characters long');
    }
    
    $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 user profile
    $city = !empty($input['city']) ? trim($input['city']) : '';
    $stmt = $pdo->prepare("UPDATE users SET name = ?, city = ? WHERE id = ?");
    $result = $stmt->execute([
        trim($input['name']), 
        $city, 
        $input['user_id']
    ]);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Profile updated successfully',
            'user_id' => $input['user_id'],
            'name' => trim($input['name']),
            'city' => $city
        ]);
    } else {
        throw new Exception('Failed to update profile');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
