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

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

if (empty($data['email']) || empty($data['full_name']) || empty($data['provider'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Email, full_name, and provider are required."]);
    exit();
}

$email = filter_var($data['email'], FILTER_SANITIZE_EMAIL);
$fullName = sanitizeInput($data['full_name']);
$provider = sanitizeInput($data['provider']);
$phone = isset($data['phone']) ? sanitizeInput($data['phone']) : '+2340000000000';

try {
    $db = getDBConnection();

    // Check if user exists
    $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    $db->beginTransaction();

    if (!$user) {
        // Automatically create a verified user for Social Login
        $randomPass = bin2hex(random_bytes(16));
        $password_hash = password_hash($randomPass, PASSWORD_BCRYPT);
        
        $stmt = $db->prepare("INSERT INTO users (full_name, email, phone, password_hash, is_verified) VALUES (?, ?, ?, ?, 1)");
        $stmt->execute([$fullName, $email, $phone, $password_hash]);
        $newUserId = $db->lastInsertId();

        // Create default wallet with ₦0.00 opening balance
        $stmt = $db->prepare("INSERT INTO wallets (user_id, balance, today_winnings) VALUES (?, 0.00, 0.00)");
        $stmt->execute([$newUserId]);

        $db->commit();

        // Fetch the newly created user
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$newUserId]);
        $user = $stmt->fetch();
    } else {
        // If user already exists but is unverified, verify them instantly
        if (intval($user['is_verified']) === 0) {
            $stmt = $db->prepare("UPDATE users SET is_verified = 1 WHERE id = ?");
            $stmt->execute([$user['id']]);
        }
        $db->commit();
    }

    // Fetch Wallet balance
    $stmt = $db->prepare("SELECT balance FROM wallets WHERE user_id = ?");
    $stmt->execute([$user['id']]);
    $wallet = $stmt->fetch();

    if (!$wallet) {
        // Edge case: create wallet if somehow missing
        $db->beginTransaction();
        $stmt = $db->prepare("INSERT INTO wallets (user_id, balance, today_winnings) VALUES (?, 0.00, 0.00)");
        $stmt->execute([$user['id']]);
        $db->commit();
        $wallet = ['balance' => 0.00];
    }

    echo json_encode([
        "status" => "success",
        "message" => "Social login successful! Connected via " . ucfirst($provider),
        "user" => [
            "id" => intval($user['id']),
            "full_name" => $user['full_name'],
            "email" => $user['email'],
            "phone" => $user['phone'],
            "avatar" => $user['avatar'] ?? null,
            "last_profile_edit" => $user['last_profile_edit'],
            "balance" => floatval($wallet['balance']),
            "today_winnings" => getTodayWinnings($user['id']),
            "points" => intval($user['points'] ?? 0),
            "points_quiz" => intval($user['points_quiz'] ?? 0),
            "points_challenges" => intval($user['points_challenges'] ?? 0),
            "points_referrals" => intval($user['points_referrals'] ?? 0),
            "points_other" => intval($user['points_other'] ?? 0),
            "influencer_status" => $user['influencer_status'] ?? null,
            "contestant_status" => $user['contestant_status'] ?? null,
            "temp_pass_active" => intval($user['temp_pass_active'] ?? 0),
            "temp_pass_expires_at" => $user['temp_pass_expires_at'] ?? null
        ]
    ]);

} catch(PDOException $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    logSecurityError("Social Login failure: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Social authentication failed. Please try again."]);
}
