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

// Enforce Rate Limiting (Max 5 login attempts per minute per IP)
checkRateLimit('login', 5, 60);

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

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

$loginInput = sanitizeInput($data['email']);
$password = $data['password'];

try {
    $db = getDBConnection();

    // Query by email OR phone
    $stmt = $db->prepare("SELECT * FROM users WHERE email = ? OR phone = ?");
    $stmt->execute([$loginInput, $loginInput]);
    $user = $stmt->fetch();

    if (!$user) {
        http_response_code(401);
        echo json_encode(["status" => "error", "message" => "No account found matching this email or phone number."]);
        exit();
    }

    // Verify Password (Secure BCRYPT verification)
    if (!password_verify($password, $user['password_hash'])) {
        http_response_code(401);
        echo json_encode(["status" => "error", "message" => "Incorrect password. Please try again."]);
        exit();
    }

    // Handle Unverified Accounts
    if (intval($user['is_verified']) === 0) {
        // Regenerate verification OTP
        $otp_code = strval(rand(100000, 999999));
        $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));

        $stmt = $db->prepare("INSERT INTO user_otps (email, code, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$user['email'], $otp_code, $expires_at]);

        http_response_code(403);
        echo json_encode([
            "status" => "unverified",
            "message" => "Your account is not verified yet. We have sent a new verification code to your email.",
            "email" => $user['email'],
            "debug_otp" => $otp_code
        ]);
        exit();
    }

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

    echo json_encode([
        "status" => "success",
        "message" => "Login successful! Welcome back.",
        "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 ? $wallet['balance'] : 0.00),
            "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) {
    logSecurityError("Login Database failure: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Login failed. Please try again."]);
}
