<?php
// um-admin/actions.php - AJAX action handler for all admin operations
require_once __DIR__ . '/auth.php';
header('Content-Type: application/json');

$action = $_POST['action'] ?? '';

function ok($data=[]) { echo json_encode(['ok'=>true]+$data); exit; }
function fail($msg) { echo json_encode(['ok'=>false,'msg'=>$msg]); exit; }

try {
    switch ($action) {

        // -- DEPOSIT: APPROVE --------------------------------------------------------
        case 'approve_deposit':
            $id = (int)($_POST['id']??0);
            $st = $pdo->prepare("SELECT * FROM deposits WHERE id=? AND status='pending'"); 
            $st->execute([$id]); 
            $dep = $st->fetch();
            if (!$dep) fail('Deposit not found or already processed');
            
            $amt = (float)$dep['amount']; 
            $uid = (int)$dep['user_id'];

            // Check first deposit (for commission calculation later)
            $isFirst = ((float)$pdo->query("SELECT COALESCE(total_deposits,0) FROM users WHERE id=$uid")->fetchColumn()) <= 0;

            $pdo->beginTransaction();
            $pdo->prepare("UPDATE deposits SET status='approved',updated_at=NOW() WHERE id=?")->execute([$id]);
            // credit balance + wager + total_deposits
            $pdo->prepare("UPDATE users SET balance=balance+?, wager=wager+?, total_deposits=COALESCE(total_deposits,0)+? WHERE id=?")->execute([$amt,$amt,$amt,$uid]);

            // Referral commissions
            $depositor = $pdo->prepare("SELECT referedby FROM users WHERE id=?"); 
            $depositor->execute([$uid]); 
            $depositor=$depositor->fetch();
            
            $rates = $isFirst ? [1=>0.26, 2=>0.10, 3=>0.05] : [1=>0.06, 2=>0.03, 3=>0.02];
            $refcode = $depositor['referedby'] ?? null;
            
            for ($lvl=1; $lvl<=3 && $refcode; $lvl++) {
                $ref = $pdo->prepare("SELECT id FROM users WHERE refercode=?"); 
                $ref->execute([$refcode]); 
                $ref=$ref->fetch();
                if (!$ref) break;
                
                $comm = round($amt * $rates[$lvl], 2);
                $pdo->prepare("INSERT INTO referral_commissions (user_id,from_user_id,deposit_id,amount,level,is_first_deposit) VALUES(?,?,?,?,?,?)")
                    ->execute([$ref['id'], $uid, $id, $comm, $lvl, $isFirst?1:0]);
                $pdo->prepare("UPDATE users SET unclaimed_earnings=COALESCE(unclaimed_earnings,0)+?, total_commission=COALESCE(total_commission,0)+? WHERE id=?")
                    ->execute([$comm, $comm, $ref['id']]);
                
                // Get next level refercode
                $nxt = $pdo->prepare("SELECT referedby FROM users WHERE id=?"); 
                $nxt->execute([$ref['id']]); 
                $nxt=$nxt->fetch();
                $refcode = $nxt['referedby'] ?? null;
            }
            $pdo->commit();
            ok(['msg'=>'Deposit approved, balance credited, commissions processed']);
            break;

        // -- DEPOSIT: REJECT ---------------------------------------------------------
        case 'reject_deposit':
            $id = (int)($_POST['id']??0);
            $reason = trim($_POST['reason']??'');
            $applyW = (int)($_POST['apply_wager']??0);
            
            if (!$reason) fail('Rejection reason required');
            $st = $pdo->prepare("SELECT * FROM deposits WHERE id=? AND status='pending'"); 
            $st->execute([$id]); 
            $dep=$st->fetch();
            
            if (!$dep) fail('Not found or already processed');
            
            $pdo->beginTransaction();
            $pdo->prepare("UPDATE deposits SET status='rejected',reject_reason=?,apply_wager=?,updated_at=NOW() WHERE id=?")
                ->execute([$reason, $applyW, $id]);
            if ($applyW) {
                $pdo->prepare("UPDATE users SET wager=COALESCE(wager,0)+? WHERE id=?")
                    ->execute([(float)$dep['amount'], (int)$dep['user_id']]);
            }
            $pdo->commit();
            ok(['msg'=>'Deposit rejected']);
            break;

        // -- WITHDRAWAL: APPROVE -----------------------------------------------------
        case 'approve_withdrawal':
            $id = (int)($_POST['id']??0);
            $st = $pdo->prepare("SELECT * FROM withdrawals WHERE id=? AND status='pending'"); 
            $st->execute([$id]); 
            $wd=$st->fetch();
            
            if (!$wd) fail('Not found or already processed');
            $amt=(float)$wd['amount']; 
            $uid=(int)$wd['user_id'];

            // Fetch Routing Config & API Credentials
            $stmt = $pdo->query("SELECT setting_key, setting_value FROM admin_settings WHERE setting_key IN ('lg_app_id', 'lg_key', 'io_app_id', 'io_key', 'io_payout_key', 'io_withdraw_pin', 'base_domain', 'payment_routing')");
            $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            $routing = json_decode($settings['payment_routing'] ?? '{}', true);
            $payout_gw = $routing['payout_gateway'] ?? 'lg_pay';
            $base_domain = rtrim($settings['base_domain'] ?? 'https://pakclub24.club', '/');
            
            $payout_order_id = "PO_" . time() . "_" . $uid . "_" . rand(1000, 9999);
            $method = strtolower($wd['method']);

            if ($payout_gw === 'io_pay') {
                $app_id = $settings['io_app_id'] ?? 'APP47be5aa3465a';
                $key = $settings['io_payout_key'] ?? '2D0B68F4496049956B6E259662FE0155';
                $pin = $settings['io_withdraw_pin'] ?? 'YourSecretWithdrawPin';
                $notify_url = "$base_domain/io_payout_webhook.php";
                
                $io_method = 'PKR'; // Jazz is PKR for withdrawal
                if (strpos($method, 'easy') !== false || $method === 'ep') $io_method = 'PKRPH-EASY';
                if (strpos($method, 'usdt') !== false) $io_method = 'usdt';
                
                $params = [
                    'app_id'            => $app_id,
                    'merchant_order_no' => $payout_order_id,
                    'amount'            => number_format((float)$amt, 2, '.', ''), // Docs show 1000.00 format for Payouts
                    'method'            => $io_method,
                    'phone'             => $wd['account_number'],
                    'holder_name'       => $wd['account_name'] ?: 'User',
                    'withdraw_password' => $pin,
                    'callback_url'      => $notify_url
                ];
                
                if ($io_method === 'usdt') {
                    // Specific fields for USDT based on docs
                    unset($params['phone']);
                    $params['network'] = 'TRC20';
                    $params['usdt_address'] = $wd['account_number'];
                }
                
                $filtered = [];
                foreach ($params as $k => $v) if ($k !== 'sign' && $v !== '' && $v !== null) $filtered[$k] = $v;
                ksort($filtered);
                $stringA = urldecode(http_build_query($filtered));
                $params['sign'] = strtoupper(md5($stringA . "&key=" . $key));
                
                $ch = curl_init('https://iopay.in/api/payout/create');
                curl_setopt_array($ch, [
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => json_encode($params),
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTPHEADER => ["Content-Type: application/json"]
                ]);
                $resp = curl_exec($ch); 
                $err = curl_error($ch); 
                curl_close($ch);
                
                if ($err) fail("cURL error: $err");
                $res = json_decode($resp, true);
                
                if (isset($res['code']) && $res['code'] == 200) {
                    $pdo->prepare("UPDATE withdrawals SET status='approved',payout_order_id=?,payout_status='processing',updated_at=NOW() WHERE id=?")->execute([$payout_order_id, $id]);
                    ok(['msg'=>'Withdrawal approved - payout sent to IO Pay']);
                } else {
                    $pdo->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$amt,$uid]);
                    $error_msg = $res['msg'] ?? 'Unknown IO-Pay Error';
                    $pdo->prepare("UPDATE withdrawals SET status='rejected',reject_reason=?,updated_at=NOW() WHERE id=?")->execute(['Payment gateway error: ' . $error_msg, $id]);
                    fail('IO Pay API error: ' . $error_msg . '. Balance refunded.');
                }
            } else {
                // LG Pay Logic
                $app_id = $settings['lg_app_id'] ?? 'PKR3245';
                $key = $settings['lg_key'] ?? 'LqpUftaBfNNyOh7YrMSXVlro7zIOj5um';
                
                if (strpos($method, 'easy') !== false || $method === 'ep') {
                    $trade_type = 'PKRPH-EASY';
                    $addon1 = 'easypaisa';
                } else {
                    $trade_type = 'PKR';
                    $addon1 = 'jazzcash';
                }

                $notify_url = "$base_domain/lg_payout_callback.php";

                $params = [
                    'app_id'      => $app_id,
                    'currency'    => $trade_type,
                    'trade_type'  => $trade_type,
                    'order_sn'    => $payout_order_id,
                    'money'       => intval($amt * 100),
                    'notify_url'  => $notify_url,
                    'name'        => $wd['account_name'],
                    'uid'         => $wd['account_number'],
                    'card_number' => $wd['account_number'],
                    'addon1'      => $addon1
                ];

                $params = array_filter($params, function($v) { return $v !== '' && $v !== null; });
                ksort($params);
                $str = urldecode(http_build_query($params)) . "&key=$key"; 
                $params['sign'] = strtoupper(md5($str));

                $ch = curl_init('https://www.lg-pay.com/api/deposit/create');
                curl_setopt_array($ch, [
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => http_build_query($params),
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_TIMEOUT => 30
                ]);
                $resp = curl_exec($ch); 
                $err = curl_error($ch); 
                curl_close($ch);
                
                if ($err) fail("cURL error: $err");
                $res = json_decode($resp, true);

                if (isset($res['status']) && $res['status'] == 1) {
                    $pdo->prepare("UPDATE withdrawals SET status='approved',payout_order_id=?,payout_status='processing',updated_at=NOW() WHERE id=?")->execute([$payout_order_id, $id]);
                    ok(['msg'=>'Withdrawal approved - payout sent to LG Pay']);
                } else {
                    $pdo->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$amt,$uid]);
                    $error_msg = $res['msg'] ?? 'Unknown Error';
                    $pdo->prepare("UPDATE withdrawals SET status='rejected',reject_reason=?,updated_at=NOW() WHERE id=?")->execute(['Payment gateway error: ' . $error_msg, $id]);
                    fail('LG Pay API error: ' . $error_msg . '. Balance refunded.');
                }
            }
            break;

        // -- WITHDRAWAL: REJECT ------------------------------------------------------
        case 'reject_withdrawal':
            $id = (int)($_POST['id']??0);
            $reason = trim($_POST['reason']??'');
            
            if (!$reason) fail('Reason required');
            $st=$pdo->prepare("SELECT * FROM withdrawals WHERE id=? AND status='pending'"); 
            $st->execute([$id]); 
            $wd=$st->fetch();
            
            if (!$wd) fail('Not found');
            
            // Refund balance since withdrawal was deducted at submission
            $pdo->beginTransaction();
            $pdo->prepare("UPDATE users SET balance=balance+? WHERE id=?")
                ->execute([(float)$wd['amount'], (int)$wd['user_id']]);
            $pdo->prepare("UPDATE withdrawals SET status='rejected',reject_reason=?,updated_at=NOW() WHERE id=?")
                ->execute([$reason, $id]);
            $pdo->commit();
            ok(['msg'=>'Withdrawal rejected, balance refunded']);
            break;

        // -- USER: EDIT BALANCE -------------------------------------------------------
        case 'edit_balance':
            $uid=(int)($_POST['uid']??0); $amt=(float)($_POST['amount']??0); $op=$_POST['op']??'add';
            if (!$uid||$amt<=0) fail('Invalid input');
            if ($op==='add') $pdo->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$amt,$uid]);
            else $pdo->prepare("UPDATE users SET balance=GREATEST(0,balance-?) WHERE id=?")->execute([$amt,$uid]);
            ok();
            break;

        // -- USER: EDIT WAGER --------------------------------------------------------
        case 'edit_wager':
            $uid=(int)($_POST['uid']??0); $amt=(float)($_POST['amount']??0); $op=$_POST['op']??'add';
            if (!$uid||$amt<=0) fail('Invalid');
            if ($op==='add') $pdo->prepare("UPDATE users SET wager=wager+? WHERE id=?")->execute([$amt,$uid]);
            else $pdo->prepare("UPDATE users SET wager=GREATEST(0,wager-?) WHERE id=?")->execute([$amt,$uid]);
            ok();
            break;

        // -- USER: BAN TOGGLE --------------------------------------------------------
        case 'ban_user':
            $uid=(int)($_POST['uid']??0);
            $cur=(int)$pdo->query("SELECT isbanned FROM users WHERE id=$uid")->fetchColumn();
            $pdo->prepare("UPDATE users SET isbanned=? WHERE id=?")->execute([$cur?0:1,$uid]);
            ok(['banned'=>!$cur]);
            break;

        // -- USER: TOGGLE DEMO -------------------------------------------------------
        case 'toggle_demo':
            $uid=(int)($_POST['uid']??0);
            if (!$uid) fail('Invalid input');
            $cur=(int)$pdo->query("SELECT is_demo FROM users WHERE id=$uid")->fetchColumn();
            $new_val = $cur ? 0 : 1;
            $pdo->prepare("UPDATE users SET is_demo=? WHERE id=?")->execute([$new_val,$uid]);
            if (isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] === $uid) {
                $_SESSION['is_demo'] = $new_val;
            }
            ok(['is_demo'=>$new_val]);
            break;

        // -- USER: LOGIN AS -----------------------------------------------------------
        case 'login_as':
            $uid=(int)($_POST['uid']??0);
            $u=$pdo->prepare("SELECT * FROM users WHERE id=?"); $u->execute([$uid]); $u=$u->fetch();
            if (!$u) fail('User not found');
            $_SESSION['admin_impersonating']=true;
            $_SESSION['user_id']=$u['id'];
            $_SESSION['phone']=$u['number'];
            $_SESSION['number']=$u['number'];
            $_SESSION['is_demo']=(int)$u['is_demo'];
            ok(['redirect'=>'../index.php']);
            break;

        // -- TICKET: REPLY ------------------------------------------------------------
        case 'reply_ticket':
            $tid=(int)($_POST['ticket_id']??0); $msg=trim($_POST['message']??'');
            if (!$tid||!$msg) fail('Missing data');
            $pdo->prepare("INSERT INTO ticket_replies (ticket_id,sender_type,message) VALUES(?,'Admin',?)")->execute([$tid,$msg]);
            $pdo->prepare("UPDATE tickets SET status='In Progress' WHERE id=? AND status='Open'")->execute([$tid]);
            ok();
            break;

        // -- TICKET: CLOSE -----------------------------------------------------------
        case 'close_ticket':
            $tid=(int)($_POST['ticket_id']??0);
            $pdo->prepare("UPDATE tickets SET status='Resolved' WHERE id=?")->execute([$tid]);
            ok();
            break;

        // -- GIFT CODE: CREATE --------------------------------------------------------
        case 'create_giftcode':
            $code=strtoupper(trim($_POST['code']??'')); $amt=(float)($_POST['amount']??0); $max=(int)($_POST['max_claims']??100);
            if (!$code||$amt<=0) fail('Invalid input');
            $pdo->prepare("INSERT INTO giftcodes (code,amount,max_claims) VALUES(?,?,?)")->execute([$code,$amt,$max]);
            ok();
            break;

        // -- GIFT CODE: TOGGLE -------------------------------------------------------
        case 'toggle_giftcode':
            $id=(int)($_POST['id']??0);
            $cur=(int)$pdo->query("SELECT status FROM giftcodes WHERE id=$id")->fetchColumn();
            $pdo->prepare("UPDATE giftcodes SET status=? WHERE id=?")->execute([$cur?0:1,$id]);
            ok(['status'=>!$cur]);
            break;

        // -- GIFT CODE: DELETE -------------------------------------------------------
        case 'delete_giftcode':
            $id=(int)($_POST['id']??0);
            $pdo->prepare("DELETE FROM giftcodes WHERE id=?")->execute([$id]);
            ok();
            break;

        default: fail('Unknown action');
    }
} catch(Exception $e) { 
    fail('Server error: '.$e->getMessage()); 
}