<?php
require_once '../config.php';

header("Content-Type: application/json; charset=UTF-8");

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

$userId = intval($data['user_id'] ?? 0);
$pitch = trim($data['pitch'] ?? '');

$profiles = $data['profiles'] ?? [];
if (!empty($profiles) && is_array($profiles)) {
    $platforms = [];
    $handles = [];
    $followers_list = [];
    foreach ($profiles as $prof) {
        if (!empty($prof['platform']) && !empty($prof['handle']) && !empty($prof['followers'])) {
            $platforms[] = trim($prof['platform']);
            $handles[] = trim($prof['handle']);
            $followers_list[] = trim($prof['followers']);
        }
    }
    $platform = implode(', ', $platforms);
    $handle = implode(', ', $handles);
    $followers = implode(', ', $followers_list);
} else {
    $handle = trim($data['handle'] ?? '');
    $platform = trim($data['platform'] ?? '');
    $followers = trim($data['followers'] ?? '');
}

if ($userId <= 0 || empty($handle) || empty($platform) || empty($followers) || empty($pitch)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "All fields are required."]);
    exit();
}

try {
    $db = getDBConnection();
    
    // Self-healing: modify column limits to accommodate multiple profiles
    try {
        $db->exec("ALTER TABLE influencers MODIFY COLUMN handle VARCHAR(255) NOT NULL");
        $db->exec("ALTER TABLE influencers MODIFY COLUMN platform VARCHAR(255) NOT NULL");
        $db->exec("ALTER TABLE influencers MODIFY COLUMN followers VARCHAR(255) NOT NULL");
    } catch (Exception $schemaEx) {
        error_log("Schema alteration warning: " . $schemaEx->getMessage());
    }

    // Check if user already applied
    $stmt = $db->prepare("SELECT id FROM influencers WHERE user_id = ?");
    $stmt->execute([$userId]);
    if ($stmt->fetch()) {
        echo json_encode(["status" => "success", "message" => "Application already submitted."]);
        exit();
    }

    $stmt = $db->prepare("INSERT INTO influencers (user_id, handle, platform, followers, pitch, status) VALUES (?, ?, ?, ?, ?, 'pending')");
    $stmt->execute([$userId, $handle, $platform, $followers, $pitch]);

    echo json_encode(["status" => "success", "message" => "Influencer application submitted successfully."]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
