<?php

header('Content-Type: application/json; charset=utf-8');

error_reporting(0); 



$conn = mysqli_connect('localhost', 'mfudevlo_batuawallet', 'batua@wallet6602#', 'mfudevlo_batuawalletdb');



if (!$conn) {

    echo json_encode([]);

    exit;

}



$mobile = isset($_GET['mobile']) ? mysqli_real_escape_string($conn, $_GET['mobile']) : '';

if (empty($mobile)) {

    echo json_encode([]);

    exit;

}



$all_data = array();



// প্রতিটি কুয়েরি আলাদা ভাবে চেক করা হয়েছে যাতে একটি টেবিল না থাকলেও এরর না আসে

$queries = [

    "SELECT 'Add Money' as type, amount, status, mobile as receiver, 'Bank' as method, '' as acc_type, '' as trx_id, created_at as date FROM add_money_requests WHERE mobile='$mobile'",

    "SELECT 'Send Money' as type, amount, status, receiver_mobile as receiver, method, acc_type, trx_id, created_at as date FROM send_money_requests WHERE sender_mobile='$mobile'",

    "SELECT 'Recharge' as type, amount, status, mobile as receiver, method, acc_type, '' as trx_id, created_at as date FROM recharge_requests WHERE mobile='$mobile'",

    "SELECT 'Offer' as type, amount, status, target_mobile as receiver, operator as method, offer_name as acc_type, '' as trx_id, created_at as date FROM offer_requests WHERE sender_mobile='$mobile'",

    "SELECT 'Pay Bill' as type, amount, status, bill_no as receiver, method, bill_type as acc_type, trx_id, created_at as date FROM pay_bill_requests WHERE user_mobile='$mobile'",

    "SELECT 'B2B' as type, amount, 'Success' as status, CASE WHEN sender_mobile = '$mobile' THEN receiver_mobile ELSE sender_mobile END as receiver, 'Internal' as method, CASE WHEN sender_mobile = '$mobile' THEN 'Sent' ELSE 'Received' END as acc_type, '' as trx_id, created_at as date FROM internal_transfers WHERE sender_mobile='$mobile' OR receiver_mobile='$mobile'"

];



foreach ($queries as $sql) {

    $res = $conn->query($sql);

    if ($res) {

        while ($row = $res->fetch_assoc()) {

            foreach($row as $key => $value){

                $row[$key] = ($value === null) ? "" : trim($value);

            }

            $all_data[] = $row;

        }

    }

}



// তারিখ অনুযায়ী সাজানো

usort($all_data, function($a, $b) {

    return strtotime($b['date']) - strtotime($a['date']);

});



echo json_encode($all_data);

?> 