<?php
require_once("../../autoloader.php");

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: User-Id, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

$response = [];
$controller = new SubscriberModel();
$controller2 = new ApiAccess();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $headers = apache_request_headers();
    $data = json_decode(file_get_contents('php://input'), true);

    $accountName   = isset($data['account_name']) ? strip_tags($data['account_name']) : '';
    $accountNumber = isset($data['account_number']) ? strip_tags($data['account_number']) : '';
    $transferType  = isset($data['transfer_type']) ? strip_tags($data['transfer_type']) : '';
    $pin           = isset($data['pin']) ? strip_tags($data['pin']) : '';
    $phone         = isset($data['email']) ? strip_tags($data['email']) : ''; // phone stored in 'email'
    $userId        = isset($data['user_id']) ? strip_tags($data['user_id']) : '';
    $amount        = isset($data['amount']) ? (float)$data['amount'] : 0;
    $transRef      = isset($data['trans_ref']) ? strip_tags($data['trans_ref']) : '';

    if (empty($phone) || $amount <= 0 || empty($transRef)) {
        echo json_encode(['status' => 'error', 'message' => 'Missing or invalid parameters']);
        exit;
    }

    date_default_timezone_set('Africa/Lagos');
    $result2 = $controller2->getSiteSettings();
    $walletCharges = (float)$result2->wallettowalletcharges;
    $amountToPay = $amount + $walletCharges;
    $transRef2 = uniqid('TRF_');
function recoverPhoneFromId(int $id): string {
    $secretKey = 57392041;
    error_log("ID INPUT: " . $id);
    $numValue = $id ^ $secretKey;
    error_log("XOR RESULT: " . $numValue);
    $decoded = str_pad($numValue, 8, '0', STR_PAD_LEFT);
    error_log("PADDED: " . $decoded);
    return '0' . $decoded;
}

  // === DEBUG - ADD THIS RIGHT BEFORE recoverPhoneFromId ===
error_log("RAW PHONE: " . $phone);
error_log("INT PHONE: " . (int)$phone);
$decodedPhone = recoverPhoneFromId((int)$phone);
error_log("RECOVERED: " . $decodedPhone);

// === YOUR EXISTING FUNCTION ===

    $decodedPhone = recoverPhoneFromId((int)$phone);

    // ... rest of your switch cases remain EXACTLY the same
    switch ($transferType) {
        case 'wallet':
            $result = $controller->performWalletTransfer($userId, $decodedPhone, $amount, $amountToPay, $transRef, $transRef2);
            break;
        case 'referral':
            $result = $controller->performReferralTransfer($userId, $amount, $amountToPay, $transRef, $transRef2);
            break;
        case 'cashback':
            $result = $controller->performCashbackTransfer($userId, $amount, $amount, $transRef);
            break;
        default:
            echo json_encode(['status' => 'error', 'message' => 'Invalid transfer type']);
            exit;
    }

    // ... all your result switch cases remain EXACTLY the same
    switch ($result) {
        case 0:
            $response = ['status' => 'success', 'message' => 'Transfer successful', 'data' => ['trans_ref' => $transRef]];
            break;
        case 2:
            $response = ['status' => 'error', 'message' => $decodedPhone];
            break;
        case 3:
            $response = ['status' => 'error', 'message' => 'Insufficient balance'];
            break;
        case 4:
            $response = ['status' => 'error', 'message' => 'Transaction recording failed'];
            break;
        case 5:
            $response = ['status' => 'error', 'message' => 'Cannot transfer to self'];
            break;
        case 6:
            $response = ['status' => 'error', 'message' => 'Invalid amount'];
            break;
        case 7:
            $response = ['status' => 'error', 'message' => 'Insufficient cashback balance'];
            break;
        default:
            $response = ['status' => 'error', 'message' => 'Unknown error occurred'];
            break;
    }
} else {
    $response = ['status' => 'error', 'message' => 'Invalid request method'];
}

echo json_encode($response);
?>