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

// ✅ Check service access
checkServiceStatus($udata, 'mobile_dth_reacharge_status');

// ✅ Load operator and commission data
$operatorsJson = XyZ_val('reacharge_apis');
$operators_arr = json_decode($operatorsJson, true);

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

// ✅ Operator list
$_C = [
    1 => ["n" => "AIRTEL", "t" => "mobile", "p" => $commission_map['Airtel']],
    2 => ["n" => "IDEA , VI", "t" => "mobile", "p" => $commission_map['Idea']],
    3 => ["n" => "VODAFONE , VI", "t" => "mobile", "p" => $commission_map['Vodafone']],
    4 => ["n" => "JIO", "t" => "mobile", "p" => $commission_map['Jio']],
    5 => ["n" => "BSNL SPECIAL", "t" => "mobile", "p" => $commission_map['Bsnl Special']],
    6 => ["n" => "BSNL TOPUP", "t" => "mobile", "p" => $commission_map['Bsnl Topup']],
];

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

// ✅ Form Submission
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 = mobile_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','Recharge Payment','1','Debit')");
            if ($c > 0)
                mysqli_query($tng_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>`,
                    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') . "'});
                document.querySelector('#rechargeBtn').disabled=false;
                document.querySelector('#rechargeBtn').innerHTML='Recharge Now';
                </script>";
        }
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
            Swal.fire({icon:'error',title:'Low Wallet Balance!',text:'Please Recharge Now!'});
            setTimeout(()=>{window.location='wallet.php';},1500);
            </script>";
    }
}

// ✅ Commission Table
$table = '<div class="table-responsive"><table class="table table-bordered table-striped text-center">';
$table .= '<thead class="table-dark"><tr><th>ID</th><th>Operator</th><th>Commission (%)</th></tr></thead><tbody>';
foreach ($operators_arr as $op) {
    $table .= "<tr>
        <td>{$op['OperatorID']}</td>
        <td>{$op['OperatorName']}</td>
        <td>{$op['Commission']}%</td>
    </tr>";
}
$table .= '</tbody></table></div>';
?>

<!-- ============================ PAGE HTML ============================ -->

<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 border-0">
            <div class="card-header bg-primary text-white fw-bold fs-5">
                <i class="bi bi-phone"></i> Mobile Recharge
            </div>
            <div class="card-body">

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

                    <!-- Mobile -->
                    <div class="col-md-12">
                        <label for="mobile" class="form-label fw-semibold">Mobile Number</label>
                        <input name="mobile" id="mobile" type="text" maxlength="10" 
                               class="form-control" placeholder="Enter 10-digit Mobile Number" required>
                    </div>

                    <!-- Operator -->
                    <div class="col-md-12">
                        <label for="operator" class="form-label fw-semibold">Select Operator</label>
                        <select name="operator" id="operator" class="form-select" 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>

                    <!-- Circle -->
                    <div class="col-md-12">
                        <label class="form-label fw-semibold">Select Circle</label>
                        <input list="circleList" id="circle" class="form-control" placeholder="Select or type circle">
                        <datalist id="circleList">
                            <option value="Andhra Pradesh & Telangana">
                            <option value="Assam">
                            <option value="Bihar & Jharkhand">
                            <option value="Delhi NCR">
                            <option value="Gujarat">
                            <option value="Haryana">
                            <option value="Himanchal Pradesh">
                            <option value="Jammu & Kashmir">
                            <option value="Karnataka">
                            <option value="Kerala">
                            <option value="Kolkata">
                            <option value="Madhya Pradesh & Chattisgarh">
                            <option value="Maharashtra & Goa">
                            <option value="Mumbai">
                            <option value="North East">
                            <option value="Odisha">
                            <option value="Punjab">
                            <option value="Rajasthan">
                            <option value="Tamil Nadu">
                            <option value="Uttar Pradesh (East)">
                            <option value="Uttar Pradesh (West) & Uttarakhand">
                            <option value="West Bengal">
                            <option value="Chennai">
                            <option value="Other">
                        </datalist>
                    </div>

                    <!-- Amount + Plans -->
                    <div class="col-md-12">
                        <label class="form-label fw-semibold">Amount / Plans</label>
                        <div class="input-group">
                            <input name="amount" id="amount" type="number" class="form-control" placeholder="Enter Amount" required>
                            <button type="button" id="viewPlans" class="btn btn-info fw-bold">
                                <i class="fa fa-list"></i> View Plans
                            </button>
                        </div>
                    </div>

                    <!-- Buttons -->
                    <div class="d-flex justify-content-between mt-3">
                        <button type="button" id="rechargeBtn" class="btn btn-primary fw-bold px-4">
                            <i class="fa fa-check-circle"></i> Recharge Now
                        </button>
                        <button type="button" id="viewCommissionBtn" class="btn btn-secondary fw-bold px-4">
                            View Commissions
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

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

// ✅ Prevent duplicate recharge
document.getElementById('rechargeBtn').addEventListener('click', function(){
    let btn = this;
    Swal.fire({
        title: 'Are you sure?',
        text: "Do you want to proceed with this recharge?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Recharge Now!',
        confirmButtonColor: '#3085d6'
    }).then(result => {
        if(result.isConfirmed){
            btn.disabled = true;
            btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
            document.getElementById('rf').submit();
        }
    });
});

// ✅ Auto-fetch operator and circle
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?.length > 0){
                    lastPlans = data.data;
                }
            }
        })
        .catch(err => console.error(err));
    }
});

// ✅ View plans popup
document.getElementById('viewPlans').addEventListener('click', function(){
    if(!lastPlans){
        Swal.fire("No Plans Found", "Please enter a 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 class="bg-dark text-white p-2 rounded">${cat.fullName} Plans</h5>
            <table class="table table-bordered table-striped">
                <thead class="table-light">
                    <tr><th>Amount</th><th>Description</th><th>Validity</th><th>Talktime</th></tr>
                </thead>
                <tbody>`;
        cat.plans.forEach(plan => {
            sectionsHtml += `
            <tr style="cursor:pointer" onclick="document.getElementById('amount').value='${plan.amount}';Swal.close();">
                <td class="bg-success text-white text-center"><b>₹${plan.amount}</b></td>
                <td>${plan.benefit}</td>
                <td class="text-center">${plan.validity}</td>
                <td class="text-center">${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");
                });
            }
        }
    });
});


document.getElementById('viewCommissionBtn').addEventListener('click', function() {
    Swal.fire({
        title: 'Operator Commissions',
        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'); ?>
