<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

if($webdata['dth_recharge_active']!=1){
    echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
    <script>
    Swal.fire({
        icon: 'error',
        title: 'Service Disabled',
        text: '🚫 DTH Recharge Service is Currently Disabled!',
        confirmButtonText: 'OK'
    }).then(() => {
        window.location='index.php';
    });
    </script>";
    include('../template/ahkweb/footer.php');
    exit;
}


$_C=[
    1=>["n"=>"AIRTEL DTH","p"=>$webdata['airtel_digital_tv_dth']],
    2=>["n"=>"DISH TV","p"=>$webdata['dishtv_dth']],
    3=>["n"=>"SUN DIRECT","p"=>$webdata['Sun_Direct_dth']],
    4=>["n"=>"TATA SKY","p"=>$webdata['tata_sky_dth']],
    5=>["n"=>"VIDEOCON D2H","p"=>$webdata['Videocon_dth']]
];

$u=$udata['phone'];
$w=$udata['balance'];

if(!empty($_POST['mobile']) && !empty($_POST['operator']) && !empty($_POST['amount'])){
    $m=$_POST['mobile'];
    $o=intval($_POST['operator']);
    $a=floatval($_POST['amount']);
    if(!isset($_C[$o])) die("<script>alert('Invalid Operator!');window.location='';</script>");
    $d=$_C[$o];
    $op=$d['n'];
    $pct=$d['p'];
    $c=round(($a*$pct)/100,2);
    if($w>=$a){
        $uurl="$tng_apiurl/api/RechargeWebService/v1/reacharge-api?mobile=$m&operator=$o&amount=$a&apikey=$tng_apikey";
        $ch=curl_init();
        curl_setopt_array($ch,[CURLOPT_URL=>$uurl,CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>30]);
        $r=json_decode(curl_exec($ch),1);
        curl_close($ch);
        if($r['Message']==="Success" && $r['sampleCode']==="200"){
            $nb=$w-$a+$c;
            mysqli_query($ahk_conn,"UPDATE users SET balance=balance-$a+$c WHERE phone='$u'");
            mysqli_query($ahk_conn,"INSERT INTO recharge_history(userid,mobile,operator,amount,status,agentid,opid,rbid,msg,commission,date) VALUES ('$u','{$r['data']['Mobile']}','$op','{$r['data']['Amount']}','{$r['data']['Status']}','{$r['data']['AgentID']}','{$r['data']['OPID']}','{$r['data']['RBID']}','{$r['data']['MSG']}','$c',NOW())");
            mysqli_query($ahk_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES ('$u','$a','$w','DTH Recharge','1','Debit')");
            if($c>0) mysqli_query($ahk_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES ('$u','$c','$nb','DTH Commission','1','Credit')");
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                  <script>Swal.fire({icon:'success',title:'DTH Recharge Success',text:'ID: {$r['data']['Mobile']} | Amount: ₹{$r['data']['Amount']} | Msg: {$r['data']['MSG']}'}).then(()=>{window.location='';});</script>";
        }else{
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
                  <script>Swal.fire({icon:'error',title:'Recharge Failed',text:'".addslashes($r['error']??'API Error')."'});</script>";
        }
    }else{
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
              <script>Swal.fire({icon:'error',title:'Wallet Balance Low!',text:'Please Recharge Now!'}).then(()=>{window.location='AddCard.php';});</script>";
    }
}
?>

<div class="content-wrap">
<div class="main">
<div class="page-wrapper">
<div class="page-content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-6 col-md-8">
<div class="card">
<div class="card-body">
<div class="alert alert-info">📺 DTH Recharge</div>
<form id="rf" action="" method="POST" class="row g-3">
<div class="form-group"><label>DTH ID</label><input name="mobile" type="text" placeholder="Enter Dth Number" class="form-control" required></div>
<div class="form-group"><label>Operator</label>
<select name="operator" class="form-control" required>
<option value="">-- Select Operator --</option>
<?php foreach($_C as $i=>$o){ ?>
<option value="<?php echo $i;?>"><?php echo $o['n']." ({$o['p']}%)";?></option>
<?php } ?>
</select></div>
<div class="form-group"><label>Amount</label><input name="amount" type="number" placeholder="Enter Amount " class="form-control" required></div>
<div class="text-end mt-3"><button type="button" class="btn btn-primary" onclick="cR()"><i class="fa fa-check-circle"></i> Recharge Now</button></div>
</form>
</div>
</div>
</div>

<?php $l=mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT * FROM recharge_history WHERE userid='$u' ORDER BY id DESC LIMIT 1")); if($l){?>
<div class="col-lg-6 col-md-4">
<div class="card" style="background:#E8F6F3;">
<div class="card-body">
<h5>Last DTH Recharge</h5>
<table class="table table-bordered">
<tr><th>ID</th><td><?php echo $l['mobile'];?></td></tr>
<tr><th>Operator</th><td><?php echo $l['operator'];?></td></tr>
<tr><th>Amount</th><td>₹<?php echo $l['amount'];?></td></tr>
<tr><th>Status</th><td><?php echo $l['status'];?></td></tr>
<tr><th>Commission</th><td>₹<?php echo $l['commission'];?></td></tr>
<tr><th>Date</th><td><?php echo $l['date'];?></td></tr>
</table>
</div>
</div>
</div><?php } ?>

</div></div></div></div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function cR(){
Swal.fire({title:'Confirm?',text:"Proceed with DTH Recharge?",icon:'warning',showCancelButton:true,confirmButtonText:'Yes, Recharge Now!'}).then(r=>{if(r.isConfirmed)document.getElementById('rf').submit()})
}
</script>
s/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
<?php include('../template/ahkweb/footer.php');?>
