<?php
include "../../conn.php";
include "../../functions2.php";

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, AR-REAL-IP');
header('Access-Control-Allow-Credentials: true');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('vary: Origin');

date_default_timezone_set("Asia/Kolkata");
$shnunc = date("Y-m-d H:i:s");

// 🔥 ERROR LOG
function masterLog($type, $message, $data = []) {
    $logFile = '/tmp/master_error_' . date('Y-m-d') . '.log';
    $time = date('Y-m-d H:i:s');
    $logData = [
        'time' => $time,
        'type' => $type,
        'message' => $message,
        'data' => $data,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN'
    ];
    $logLine = json_encode($logData, JSON_UNESCAPED_UNICODE) . "\n";
    error_log($logLine, 3, $logFile);
}

$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $shnunc,
];

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

// 🔥 DEBUG LOG
masterLog('DEBUG', 'Request received', [
    'raw_body' => $shonubody,
    'parsed' => $shonupost
]);

// 🔴 METHOD CHECK
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    masterLog('ERROR', 'GET method not allowed');
    http_response_code(405);
    echo json_encode($res);
    exit;
}

// Check if JSON valid
if (!is_array($shonupost)) {
    masterLog('ERROR', 'Invalid JSON', ['raw' => $shonubody]);
    $res['code'] = 7;
    $res['msg'] = 'Invalid JSON format';
    $res['msgCode'] = 6;
    echo json_encode($res);
    exit;
}

// ==========================================================
// ✅ EXTRACT ALL FIELDS (Jo bhi aaye, sab lo)
// ==========================================================

// Required fields
$username = isset($shonupost['username']) ? $shonupost['username'] : null;
$pwd = isset($shonupost['pwd']) ? $shonupost['pwd'] : null;

if (empty($username) || empty($pwd)) {
    masterLog('ERROR', 'Missing username or pwd', ['received' => $shonupost]);
    $res['code'] = 7;
    $res['msg'] = 'Param is Invalid: username and pwd required';
    $res['msgCode'] = 6;
    echo json_encode($res);
    exit;
}

// Sab fields nikalo (chahe empty ho)
$captchaId = isset($shonupost['captchaId']) ? $shonupost['captchaId'] : '';
$deviceId = isset($shonupost['deviceId']) ? $shonupost['deviceId'] : '';
$language = isset($shonupost['language']) ? intval($shonupost['language']) : 0;
$logintype = isset($shonupost['logintype']) ? $shonupost['logintype'] : 'mobile';
$packId = isset($shonupost['packId']) ? $shonupost['packId'] : '';
$phonetype = isset($shonupost['phonetype']) ? intval($shonupost['phonetype']) : 0;
$random = isset($shonupost['random']) ? $shonupost['random'] : '';
$signature = isset($shonupost['signature']) ? $shonupost['signature'] : '';
$timestamp = isset($shonupost['timestamp']) ? intval($shonupost['timestamp']) : time();
$track = isset($shonupost['track']) ? $shonupost['track'] : null;

// 91 prefix hatao for local DB
$usernameLocal = $username;
if (substr($usernameLocal, 0, 2) == "91") {
    $usernameLocal = substr($usernameLocal, 2);
}

masterLog('INFO', 'All vars extracted', [
    'username' => $username,
    'usernameLocal' => $usernameLocal,
    'has_captchaId' => !empty($captchaId),
    'has_deviceId' => !empty($deviceId),
    'has_signature' => !empty($signature)
]);

// ==========================================================
// STEP 1: CHECK LOCAL DB
// ==========================================================

$userFound = false;
$needApi = false;

if ($logintype == 'email') {
    $sql = "SELECT * FROM shonu_subjects WHERE email='$usernameLocal'";
} else {
    $sql = "SELECT * FROM shonu_subjects WHERE mobile='$usernameLocal'";
}

$result = $conn->query($sql);
$row = $result ? $result->fetch_assoc() : null;

if ($row) {
    masterLog('DB_FOUND', 'User exists locally', ['id' => $row['id']]);
    
    if ($row['password'] === md5($pwd)) {
        $userFound = true;
        $userId = $row['id'];
        $mobile = $row['mobile'];
        $nickName = $row['codechorkamukala'];
        $status = $row['status'];
        masterLog('DB_LOGIN_OK', 'Local login success');
    } else {
        $needApi = true;
        masterLog('DB_PASS_WRONG', 'Wrong password, trying API');
    }
} else {
    $needApi = true;
    masterLog('DB_NOT_FOUND', 'User not in DB, trying API');
}

// ==========================================================
// STEP 2: CALL REAL API (SikkimGG)
// ==========================================================

if ($needApi) {
    
    $apiUrl = "https://api.tashanrfv.com/api/webapi/Login";
    
    masterLog('API_CALL', 'Calling real API', ['url' => $apiUrl]);
    
    // 🔥 EXACT SAME PAYLOAD jo frontend bhej raha hai
    $apiPayload = [
        'captchaId' => $captchaId,
        'deviceId' => $deviceId,
        'language' => $language,
        'logintype' => $logintype,
        'packId' => $packId,
        'phonetype' => $phonetype,
        'pwd' => $pwd,
        'random' => $random,
        'signature' => $signature,
        'timestamp' => $timestamp,
        'username' => $username
    ];
    
    // Track agar hai toh add karo
    if ($track !== null) {
        $apiPayload['track'] = $track;
    }
    
    // Empty fields hata do (optional)
    if (empty($captchaId)) unset($apiPayload['captchaId']);
    if (empty($deviceId)) unset($apiPayload['deviceId']);
    if (empty($packId)) unset($apiPayload['packId']);
    
    $jsonData = json_encode($apiPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    
    masterLog('API_PAYLOAD', 'Sending to real API', [
        'payload' => $apiPayload,
        'json' => $jsonData
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    masterLog('API_RESPONSE', 'Got response', [
        'http' => $httpCode,
        'error' => $curlError,
        'raw' => $response
    ]);
    
    if ($curlError) {
        masterLog('API_CURL_FAIL', $curlError);
        
        // CURL fail? Local try karo
        if ($row && $row['password'] === md5($pwd)) {
            $userFound = true;
            $userId = $row['id'];
            $mobile = $row['mobile'];
            $nickName = $row['codechorkamukala'];
            $status = $row['status'];
        }
    } else {
        $apiRes = json_decode($response, true);
        
        masterLog('API_PARSED', 'Parsed response', $apiRes);
        
        if (isset($apiRes['code']) && $apiRes['code'] === 0) {
            // ✅ SUCCESS
            masterLog('API_LOGIN_OK', 'Real API success');
            
            $apiUser = $apiRes['data'] ?? [];
            $apiMobile = $apiUser['userName'] ?? $apiUser['username'] ?? $username;
            $apiNick = $apiUser['nickName'] ?? 'Member';
            
            // 91 hatao
            $mobileClean = $apiMobile;
            if (substr($mobileClean, 0, 2) == "91") {
                $mobileClean = substr($mobileClean, 2);
            }
            
            // Save to DB
            $check = $conn->query("SELECT id FROM shonu_subjects WHERE mobile='$mobileClean'");
            
            if ($check && $check->num_rows > 0) {
                // Update
                $ex = $check->fetch_assoc();
                $userId = $ex['id'];
                
                $up = "UPDATE shonu_subjects SET 
                    password='" . md5($pwd) . "',
                    codechorkamukala='" . $conn->real_escape_string($apiNick) . "',
                    status=1,
                    shonullgnt='$shnunc'
                    WHERE id=$userId";
                
                $conn->query($up);
                masterLog('DB_UPDATE', 'Updated user', ['id' => $userId]);
                
            } else {
                // Insert new
                $code = 'MEM' . rand(1000,9999);
                $own = 'OWN' . rand(10000,99999);
                
                $ins = "INSERT INTO shonu_subjects 
                    (mobile, password, status, codechorkamukala, createdate, ishonup, owncode, privacy, code)
                    VALUES ('$mobileClean', '" . md5($pwd) . "', 1, '" . $conn->real_escape_string($apiNick) . "', '$shnunc', 'API', '$own', '0', '" . rand(100000,999999) . "')";
                
                $conn->query($ins);
                $userId = $conn->insert_id;
                
                $conn->query("INSERT INTO shonu_kaichila (balakedara, motta) VALUES ($userId, 0.00)");
                masterLog('DB_INSERT', 'New user', ['id' => $userId]);
            }
            
            $mobile = $mobileClean;
            $nickName = $apiNick;
            $status = 1;
            $userFound = true;
            
        } else {
            // ❌ API FAILED
            masterLog('API_LOGIN_FAIL', 'Real API rejected', [
                'code' => $apiRes['code'] ?? '?',
                'msg' => $apiRes['msg'] ?? 'Unknown'
            ]);
            
            // Return same error to frontend
            echo json_encode($apiRes);
            exit;
        }
    }
}

// ==========================================================
// STEP 3: SUCCESS RESPONSE
// ==========================================================

if (!$userFound || $status != 1) {
    $res['code'] = 1;
    $res['msg'] = 'Login failed';
    $res['msgCode'] = 101;
    echo json_encode($res);
    exit;
}

// Generate tokens
$data = [
    'expiresIn' => time() + 86400,
    'tokenHeader' => 'Bearer ',
    'passwordErrorNum' => 0,
    'passwordErrorMaxNum' => 30
];

$header = ['alg' => 'HS256', 'typ' => 'JWT'];
$payload = [
    'id' => $userId,
    'mobile' => $mobile,
    'status' => 1,
    'expire' => $data['expiresIn'],
    'codechorkamukala' => $nickName
];

$data['token'] = generate_jwt($header, $payload);
$data['refreshToken'] = generate_jwt($header, $payload);

// Update login info
$ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

$conn->query("UPDATE shonu_subjects SET 
    shonupwderr=0, 
    ishonup='$ip', 
    shonullgnt='$shnunc', 
    akshinak='{$data['token']}', 
    tnegaresunohs='" . $conn->real_escape_string($ua) . "' 
    WHERE id=$userId");

// Notification
$conn->query("INSERT INTO notification (state, title, user_id, created_at) VALUES (0, 'Login', $userId, '$shnunc')");

// ✅ SUCCESS
$res = [
    'code' => 0,
    'msg' => 'Succeed',
    'msgCode' => 0,
    'serviceNowTime' => $shnunc,
    'data' => $data
];

masterLog('LOGIN_SUCCESS', 'Done', ['userId' => $userId]);

echo json_encode($res);
?>