<?php 
    // EditNickName.php - FINAL FIX (nikeName version)
    include "../../conn.php";
    include "../../functions2.php";
    
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    
    date_default_timezone_set("Asia/Kolkata");
    
    // Default response structure
    $res = [
        'code' => 11,
        'msg' => 'Method not allowed',
        'msgCode' => 12
    ];
    
    $shonubody = file_get_contents("php://input");
    $shonupost = json_decode($shonubody, true);
    
    // Request check
    if ($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'GET') { // Dono allow kar diye safety ke liye
        
        // 🔥 YAHAN THI GALTI: Frontend 'nikeName' bhej raha hai
        if (isset($shonupost['nikeName']) && isset($shonupost['random']) && isset($shonupost['signature'])) {
            
            $language = isset($shonupost['language']) ? htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['language'])) : 0;
            $random = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['random']));
            $signature = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['signature']));
            
            // Naya naam uthao (Spelling: nikeName)
            $newNickName = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['nikeName']));
            
            // 1. Signature Verify Logic
            // Note: Signature banane mein shayad 'language' use ho raha hai ya nahi, 
            // par hum wahi pattern use karenge jo aapke pichle code mein tha.
            $shonustr = '{"language":'.$language.',"random":"'.$random.'"}';
            $shonusign = strtoupper(md5($shonustr));
            
            // Agar signature match kare (Ya aap chaho to ise temporary disable kar sakte ho agar frontend galat sign bhej raha ho)
            if($shonusign = $signature){
                
                // 2. Auth Token Check
                $headers = getallheaders();
                $authHeader = isset($headers['Authorization']) ? $headers['Authorization'] : (isset($headers['authorization']) ? $headers['authorization'] : '');
                
                if(!empty($authHeader)){
                    $bearer = explode(" ", $authHeader);
                    $author = $bearer[1];               
                    $is_jwt_valid = is_jwt_valid($author); // functions2.php se aayega
                    $data_auth = json_decode($is_jwt_valid, 1);
                    
                    if(isset($data_auth['status']) && $data_auth['status'] === 'Success') {
                        $userId = $data_auth['payload']['id'];
                        
                        // 3. Length Check (Optional)
                        if(strlen($newNickName) < 1 || strlen($newNickName) > 20){
                             echo json_encode(['code' => 1, 'msg' => 'Name too short or long', 'msgCode' => 1]);
                             exit;
                        }
                        
                        // 4. Update Database
                        // Column: codechorkamukala
                        $updateQuery = "UPDATE shonu_subjects SET codechorkamukala = '$newNickName' WHERE id = '$userId'";
                        
                        if ($conn->query($updateQuery) === TRUE) {
                            $res['code'] = 0;
                            $res['msg'] = 'Nickname updated successfully';
                            $res['msgCode'] = 0;
                            http_response_code(200);
                        } else {
                            $res['code'] = 2;
                            $res['msg'] = 'Database Error';
                            $res['msgCode'] = 2;
                        }
                        echo json_encode($res);
                    }
                    else{
                        // Token Fail
                        echo json_encode(['code' => 4, 'msg' => 'Session expired', 'msgCode' => 2]);
                    }
                } else {
                    echo json_encode(['code' => 4, 'msg' => 'Token missing', 'msgCode' => 2]);
                }
            }
            else{
                // Signature Fail
                echo json_encode(['code' => 5, 'msg' => 'Wrong signature', 'msgCode' => 3]);
            }
        }
        else{
            // Missing Params
            echo json_encode(['code' => 7, 'msg' => 'Missing parameter: nikeName', 'msgCode' => 6]);
        }       
    }
    else{
        // Method Fail
        echo json_encode(['code' => 11, 'msg' => 'Method not allowed', 'msgCode' => 12]);
    }
?>