<?php
function parseCookies($cookieStr) {
    $cookies = [];
    $cookieList = explode(";", $cookieStr);
    foreach ($cookieList as $cookie) {
        if (strpos($cookie, "=") !== false) {
            list($key, $value) = explode("=", trim($cookie), 2);
            $cookies[$key] = $value;
        }
    }
    return $cookies;
}

function extractPHPSESSID($cookieHeader) {
    preg_match('/PHPSESSID=([a-zA-Z0-9]+)/', $cookieHeader, $matches);
    return $matches[1] ?? null;
}

function getRandomProxy() {
    $proxies = [
        "gw.dataimpulse.com:823:66b3e03983f292d4ccfd__cr.gb,us,ph,in,bd:f22dd3f4e73fd916",
        "gw.dataimpulse.com:823:66b3e03983f292d4ccfd__cr.gb,us,ph,in,bd:f22dd3f4e73fd916",
        "gw.dataimpulse.com:823:66b3e03983f292d4ccfd__cr.gb,us,ph,in,bd:f22dd3f4e73fd916",
        "gw.dataimpulse.com:823:66b3e03983f292d4ccfd__cr.gb,us,ph,in,bd:f22dd3f4e73fd916",
        "gw.dataimpulse.com:823:66b3e03983f292d4ccfd__cr.gb,us,ph,in,bd:f22dd3f4e73fd916"
    ];

    return $proxies[array_rand($proxies)];
}

function VALIDASI_LOGIN($cookieStr) {
    $cookies = parseCookies($cookieStr);
    
    $headers = [
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding: gzip, deflate",
        "Accept-Language: en,id-ID;q=0.9,id;q=0.8,en-US;q=0.7",
        "Connection: keep-alive",
        "Host: dj.yogram.net",
        "X-Requested-With: djliker.app",
        "User-Agent: Mozilla/5.0 (Linux; Android 13; SM-S908U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Mobile Safari/537.36"
    ];

    // Select a random proxy
    $proxy = getRandomProxy();
    list($proxyHost, $proxyPort, $proxyUser, $proxyPass) = explode(":", $proxy);

    $ch = curl_init();

    // Step 1: First request to establish a session
    curl_setopt($ch, CURLOPT_URL, "https://dj.yogram.net/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1); // Capture headers to get cookies
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_COOKIE, $cookieStr);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // Set proxy
    curl_setopt($ch, CURLOPT_PROXY, $proxyHost);
    curl_setopt($ch, CURLOPT_PROXYPORT, $proxyPort);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$proxyUser:$proxyPass");

    $response1 = curl_exec($ch);

    if (!$response1) {
        return ["message" => "Request failed! " . curl_error($ch), "success" => false];
    }

    // Extract PHPSESSID from Set-Cookie header
    preg_match_all('/Set-Cookie: (.*?);/i', $response1, $matches);
    $cookieHeader = implode("; ", $matches[1]);
    $phpSessionId = extractPHPSESSID($cookieHeader);
    
    // Use the received cookies for the next request
    curl_setopt($ch, CURLOPT_COOKIE, $cookieHeader);

    // Step 2: Login request
    $params = [
        "device_name" => "SM-S908U",
        "cookie" => $cookieStr,
        "token" => "",
        "manufacturer" => "SAMSUNG"
    ];
    
    $queryParams = http_build_query($params);
    curl_setopt($ch, CURLOPT_URL, "https://dj.yogram.net/login.php?" . $queryParams);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    $response2 = curl_exec($ch);
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    curl_close($ch);

    if (strpos($finalUrl, "update.php?error=") !== false) {
        return ["message" => "This application requires an update!", "success" => false];
    } elseif (strpos($finalUrl, "?i=Welcome") !== false) {
        $result = ["message" => "Login successful", "success" => true];
        if ($phpSessionId) {
            $result["PHPSESSID"] = $phpSessionId;
            $result["cookies"] = $cookieHeader;  // Return all session cookies
        }
        return $result;
    } else {
        return ["message" => "Login failed! Check your cookies.", "success" => false];
    }
}

if (isset($_GET['cookie'])) {
    header('Content-Type: application/json');
    echo json_encode(VALIDASI_LOGIN($_GET['cookie']));
} else {
    echo json_encode(["message" => "Cookie is required", "success" => false]);
}
?>
