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

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

$_C=[1=>["n"=>"AIRTEL","t"=>"mobile","p"=>$webdata['airtal']],
     2=>["n"=>"IDEA , VI","t"=>"mobile","p"=>$webdata['vi']],
     3=>["n"=>"VODAFONE , VI","t"=>"mobile","p"=>$webdata['vi']],
     4=>["n"=>"JIO","t"=>"mobile","p"=>$webdata['jio']],
     5=>["n"=>"BSNL SPECIAL","t"=>"mobile","p"=>$webdata['bsnl']],
     6=>["n"=>"BSNL TOPUP","t"=>"mobile","p"=>$webdata['bsnl']]];

$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','Recharge Payment','1','Debit')");
            if($c>0)mysqli_query($ahk_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES ('$u','$c','$nb','Recharge Commission','1','Credit')");

            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
            Swal.fire({icon:'success',title:'Recharge Successful ✅',
                html:'<div style=\"text-align:left;font-size:16px;\"><p><strong>Mobile:</strong> <span style=\"color:#1E88E5;\">{$r['data']['Mobile']}</span></p><p><strong>Amount:</strong> <span style=\"color:#FB8C00;\">₹{$r['data']['Amount']}</span></p><p><strong>Message:</strong> <span style=\"color:#43A047;\">{$r['data']['MSG']}</span></p></div>',
                showConfirmButton:true,confirmButtonText:'OK',confirmButtonColor:'#4CAF50'}).then(()=>{window.location='reacharge_history.php';});
            </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 is Low!',text:'Please Recharge Now!'});setTimeout(()=>{window.location='wallet.php';},1500);</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-8 col-md-10 mx-auto">
<div class="card shadow-lg">
<div class="card-body">
<div class="alert alert-info fw-bold" role="alert">📱 Mobile Recharge</div>

<form id="rf" action="" method="POST" class="row g-3">

    <!-- Mobile -->
    <div class="form-group">
        <label for="mobile">Mobile Number</label>
        <input name="mobile" id="mobile" type="text" 
               class="form-control" placeholder="Enter Mobile Number" 
               maxlength="10" required>
    </div>

    <!-- Operator -->
    <div class="form-group">
        <label for="operator">Select Operator</label>
        <select name="operator" id="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 for="circle">Circle</label>
    <input list="circleList" id="circle" class="form-control" placeholder="Select or type circle">
    <datalist id="circleList">
          <option value="" selected disabled>Select Circle</option>
        <option value="Andhra Pradesh & Telangana">Andhra Pradesh & Telangana</option>
        <option value="Assam">Assam</option>
        <option value="Bihar & Jharkhand">Bihar & Jharkhand</option>
        <option value="Delhi NCR">Delhi NCR</option>
        <option value="Gujarat">Gujarat</option>
        <option value="Haryana">Haryana</option>
        <option value="Himanchal Pradesh">Himanchal Pradesh</option>
        <option value="Jammu & Kashmir">Jammu & Kashmir</option>
        <option value="Karnataka">Karnataka</option>
        <option value="Kerala">Kerala</option>
        <option value="Kolkata">Kolkata</option>
        <option value="Madhya Pradesh & Chattisgarh">Madhya Pradesh & Chattisgarh</option>
        <option value="Maharashtra & Goa">Maharashtra & Goa</option>
        <option value="Mumbai">Mumbai</option>
        <option value="North East">North East</option>
        <option value="Odisha">Odisha</option>
        <option value="Punjab">Punjab</option>
        <option value="Rajasthan">Rajasthan</option>
        <option value="Tamil Nadu">Tamil Nadu</option>
        <option value="Uttar Pradesh (East)">Uttar Pradesh (East)</option>
        <option value="Uttar Pradesh (West) & Uttarakhand">Uttar Pradesh (West) & Uttarakhand</option>
        <option value="West Bengal">West Bengal</option>
        <option value="Chennai">Chennai</option>
        <!-- Optional manual input -->
        <option value="Other">Other</option>
   
        <!-- API se aane wala circles yahan append honge -->
    </datalist>
</div>

   <!-- Amount + Plans -->
<div class="form-group">
    <label>Amount / Plans</label>
    <div class="d-flex gap-2 align-items-center">
        <!-- Input: 70% width -->
        <input name="amount" id="amount" type="number" 
               class="form-control" 
               style="flex: 0 0 70%;" 
               placeholder="Enter Amount" required>
        
        <!-- Button: 30% width -->
        <button type="button" id="viewPlans" 
                class="btn btn-info fw-bold" 
                style="flex: 0 0 30%;">
            <i class="fa fa-list"></i> View Plans
        </button>
    </div>
</div>


   <div class="d-flex justify-content-center 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>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let lastPlans = null; // cache plans

function cR(){
    Swal.fire({
        title:'Are you sure?',
        text:"Do you want to proceed with this recharge?",
        icon:'warning',
        showCancelButton:true,
        confirmButtonColor:'#3085d6',
        cancelButtonColor:'#d33',
        confirmButtonText:'Yes, Recharge Now!'
    }).then(r=>{
        if(r.isConfirmed) document.getElementById('rf').submit();
    })
}

// Auto-fetch operator + circle + plans
document.getElementById('mobile').addEventListener('input', function(){
    let mob = this.value.trim();
    if(mob.length===10){
        fetch(`proxy.php?mobile=${mob}`)
        .then(res => res.json())
        .then(data => {
            if(data.Message === "Success"){
                document.getElementById('circle').value = data.circle;
                if(data.operator_id){
                    document.getElementById('operator').value = data.operator_id;
                }
                if(data.data && data.data.length > 0){
                    lastPlans = data.data;
                }
            }
        })
        .catch(err => console.log(err));
    }
});

// View Plans
document.getElementById('viewPlans').addEventListener('click', function(){
    if(!lastPlans){
        Swal.fire("No Plans Found","Please enter valid 10 digit mobile number first!","warning");
        return;
    }

    let tabsHtml = `<div style="margin-bottom:15px;display:flex;gap:10px;overflow-x:auto">`;
    lastPlans.forEach((cat, index) => {
        tabsHtml += `<button class="tab-btn" onclick="showPlans(${index})" 
            style="padding:6px 15px;border:none;border-radius:20px;
            background:${index===0?'#007bff':'#f0f0f0'};
            color:${index===0?'#fff':'#000'};
            cursor:pointer;white-space:nowrap;font-weight:600">
            ${cat.fullName}</button>`;
    });
    tabsHtml += `</div>`;

    let sectionsHtml = "";
    lastPlans.forEach((cat, index) => {
        sectionsHtml += `
        <div class="plan-section" id="plans-${index}" style="display:${index===0?'block':'none'};max-height:400px;overflow:auto">
            <h5 style="background:#343a40;color:#fff;padding:8px 12px;border-radius:6px;margin-bottom:10px;font-size:16px">
                ${cat.fullName} Plans
            </h5>
            <table class="table table-bordered table-striped" style="width:100%;border-collapse:collapse;font-size:14px">
                <thead style="background:#f8f9fa">
                    <tr>
                        <th style="text-align:center">Amount</th>
                        <th>Description</th>
                        <th style="text-align:center">Validity</th>
                        <th style="text-align:center">Talktime</th>
                    </tr>
                </thead>
                <tbody>`;

        cat.plans.forEach(plan => {
            sectionsHtml += `
                <tr style="cursor:pointer" 
                    onclick="document.getElementById('amount').value='${plan.amount}';Swal.close();">
                    <td style="text-align:center;color:#fff;background:#28a745;padding:6px;border-radius:4px"><b>₹${plan.amount}</b></td>
                    <td style="padding:6px">${plan.benefit}</td>
                    <td style="text-align:center;padding:6px">${plan.validity}</td>
                    <td style="text-align:center;padding:6px">${plan.talktime}</td>
                </tr>`;
        });

        sectionsHtml += `</tbody></table></div>`;
    });

    Swal.fire({
        title: "Available Plans",
        html: tabsHtml + sectionsHtml,
        width: '850px',
        showCloseButton: true,
        showConfirmButton: false,
        didOpen: () => {
            window.showPlans = function(index){
                document.querySelectorAll(".plan-section").forEach((el,i)=>el.style.display = (i===index ? "block":"none"));
                document.querySelectorAll(".tab-btn").forEach((btn,i)=>{
                    btn.style.background = (i===index ? "#007bff":"#f0f0f0");
                    btn.style.color = (i===index ? "#fff":"#000");
                });
            }
        }
    });
});
</script>

<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/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');?>
