<?php

header('Content-Type: application/json');

// Require auth via cookie
if (!isset($_COOKIE['user_id'])) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Not authenticated"]);
    exit;
}

$userId = $_COOKIE['user_id'];

require_once __DIR__ . '/../config.php';

// Read JSON body
$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);

if (!is_array($payload)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Invalid JSON body"]);
    exit;
}

$authToken    = isset($payload['authToken']) ? $payload['authToken'] : null;
$console_user = isset($payload['console_user']) ? $payload['console_user'] : null;
$user_uid     = isset($payload['user_uid']) ? $payload['user_uid'] : null;

$profileInfo  = isset($payload['profileInfo']) && is_array($payload['profileInfo']) ? $payload['profileInfo'] : [];
$firstName    = isset($profileInfo['firstName']) ? $profileInfo['firstName'] : '';
$lastName     = isset($profileInfo['lastName']) ? $profileInfo['lastName'] : '';
$title        = isset($profileInfo['title']) ? $profileInfo['title'] : '';
$connects     = isset($profileInfo['connectsBalance']) ? (int)$profileInfo['connectsBalance'] : 0;
$image        = isset($profileInfo['portrait']['portrait100']) ? $profileInfo['portrait']['portrait100'] : '';

$name = trim($firstName . ' ' . $lastName);

// Basic validation
if (!$authToken || !$user_uid) {
    http_response_code(422);
    echo json_encode(["status" => "error", "message" => "Missing required fields"]);
    exit;
}

// Escape values
$userIdEsc     = mysqli_real_escape_string($conn, $userId);
$authTokenEsc  = mysqli_real_escape_string($conn, $authToken);
$consoleUserEsc= mysqli_real_escape_string($conn, $console_user);
$userUidEsc    = mysqli_real_escape_string($conn, $user_uid);
$nameEsc       = mysqli_real_escape_string($conn, $name);
$titleEsc      = mysqli_real_escape_string($conn, $title);
$connectsEsc   = (int)$connects;
$imageEsc      = mysqli_real_escape_string($conn, $image);

date_default_timezone_set('UTC');
$now = date('Y-m-d H:i:s');
$nowEsc = mysqli_real_escape_string($conn, $now);

// Check if record exists
$checkSql = "SELECT id FROM upwork WHERE user_id = '$userIdEsc' LIMIT 1";
$checkRes = mysqli_query($conn, $checkSql);

if ($checkRes && mysqli_num_rows($checkRes) > 0) {
    // Update
    $updateSql = "UPDATE upwork SET token = '$authTokenEsc', user_uid = '$userUidEsc', console_user = '$consoleUserEsc', name = '$nameEsc', title = '$titleEsc', connects = $connectsEsc, `image` = '$image', updated_at = '$nowEsc' WHERE user_id = '$userIdEsc'";
    if (mysqli_query($conn, $updateSql)) {
        echo json_encode(["status" => "ok", "action" => "updated"]);
        exit;
    } else {
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to update record"]);
        exit;
    }
} else {
    // Insert
    $insertSql = "INSERT INTO upwork (user_id, token, user_uid, console_user, name, title, connects, `image`, updated_at, created_at) VALUES ('$userIdEsc', '$authTokenEsc', '$userUidEsc', '$consoleUserEsc', '$nameEsc', '$titleEsc', $connectsEsc, '$image', '$nowEsc', '$nowEsc')";
    if (mysqli_query($conn, $insertSql)) {
        $settingsQuery = "INSERT INTO `upwork_settings` (`user_id`, `search`, `price_percentage`, `job_type`, `hourly_rates`, `contractor_tier`, `workload`, `duration`, `location`, `client_hires`, `verified_payment`, `proposals`, `budget`, `updated_at`, `created_at`) VALUES ($userIdEsc, 'web developer', 80, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, '$nowEsc', '$nowEsc')";
        mysqli_query($conn, $settingsQuery);
        $aiQuery = "INSERT INTO `upwork_ai` (`user_id`, `words`, `instructions`) VALUES ($userIdEsc, 100, 'You are a professional AI assistant that can help me with my work. You are very helpful and always willing to help.')";
        mysqli_query($conn, $aiQuery);
        echo json_encode(["status" => "ok", "action" => "inserted"]);
        exit;
    } else {
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to insert record"]);
        exit;
    }
}
