<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
checkServiceStatus($udata, 'mobile_dth_reacharge_status');

$operatorsJson = XyZ_val('reacharge_apis');
$operators_arr = json_decode($operatorsJson, true);

$commission_map = [];
foreach($operators_arr as $op){
    $commission_map[$op['OperatorName']] = $op['Commission'];
}

$_C = [
    7 => ["n"=>"AIRTEL DIGITAL TV","t"=>"tv","p"=>$commission_map['Airtel Digital TV']],
    8 => ["n"=>"DISH TV","t"=>"tv","p"=>$commission_map['Dish TV']],
    9 => ["n"=>"SUN DIRECT","t"=>"tv","p"=>$commission_map['Sun Direct']],
    10 => ["n"=>"TATA SKY","t"=>"tv","p"=>$commission_map['Tata Sky']],
    11 => ["n"=>"VIDEOCON D2H","t"=>"tv","p"=>$commission_map['Videocon D2H']],
];

$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){
        $request = [
        'mobile' => $m,
        'operator' => $o,
        'amount' => $a,
        ];

        $r = dth_reacharge_api_verification_api_run($request);
        if($r['Message']==="Success" && $r['sampleCode']==="200"){
            $nb=$w-$a+$c;
            mysqli_query($tng_conn,"UPDATE users SET balance=balance-$a+$c WHERE phone='$u'");
            mysqli_query($tng_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($tng_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES ('$u','$a','$w','DTH Recharge','1','Debit')");
            if($c>0) mysqli_query($tng_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>";
    }
}
$table = '<table border="1" style="width:100%;text-align:left;border-collapse:collapse">';
$table .= '<tr><th>ID</th><th>Operator</th><th>Commission</th></tr>';
foreach($operators_arr as $op){
    $table .= '<tr>';
    $table .= '<td>'.$op['OperatorID'].'</td>';
    $table .= '<td>'.$op['OperatorName'].'</td>';
    $table .= '<td>'.$op['Commission'].'%</td>'; 
    $table .= '</tr>';
}
$table .= '</table>';
?>

<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="mb-4">
  <a href="javascript:history.back()" class="back-btn">
    <i class="bi bi-arrow-left-circle"></i> Go Back
  </a>
</div>
    
<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="d-flex justify-content-between mt-3">
    <!-- Left button -->
    <button type="button" class="btn btn-primary" onclick="cR()">
        <i class="fa fa-check-circle"></i> Recharge Now
    </button>

    <!-- Right button -->
    <button id="viewCommissionBtn" class="btn btn-secondary">
        View Commissions
    </button>
</div>
</form>
</div>
</div>
</div>

<?php $l=mysqli_fetch_assoc(mysqli_query($tng_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>
let isSubmitting = false;

function cR(){
    if(isSubmitting) return;
    Swal.fire({
        title: 'Confirm?',
        text: "Proceed with DTH Recharge?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Recharge Now!'
    }).then(r => {
        if(r.isConfirmed){
            isSubmitting = true; 
            document.getElementById('rf').submit();
        }
    });
}
</script>
<script>
document.getElementById('viewCommissionBtn').addEventListener('click', function() {
    Swal.fire({
        title: 'Operators Commission',
        html: `<?php echo $table; ?>`,
        width: '600px',
        confirmButtonText: 'Close'
    });
});
</script>
<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
<?php include('../template/tngweb/footer.php');?>
