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

$fee = $udata['mobile_2_pan'] ?? 0;
checkServiceStatus($udata, 'mobile_2_pan_status');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['mobileNumber']) && !empty($_POST['name'])) {

    $mobile = trim($_POST['mobileNumber']);
    $name   = trim($_POST['name']);
    $user   = $udata['phone'];
    $wallet = (float) $udata['balance'];

   
    if (!preg_match('/^[6-9]\d{9}$/', $mobile)) {
        echo "<script>
            Swal.fire('Invalid Mobile','Enter valid 10 digit mobile number','error');
        </script>";
        exit;
    }

  
    if ($wallet < $fee) {
        echo "<script>
            Swal.fire('Wallet Low','Please recharge wallet','error')
            .then(()=>window.location='wallet.php');
        </script>";
        exit;
    }

   
    $resdata = mobile_number_to_pan_verification_api_run([
        'mobileNumber' => $mobile,
        'name'         => $name
    ]);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['message'] ?? $resdata['error'] ?? 'PAN not found';


    if ((string)$sampleCode !== "200") {
        echo "<script>
            Swal.fire('Failed','".addslashes($errorMsg)."','error');
        </script>";
        exit;
    }

    $stmt = $tng_conn->prepare("UPDATE users SET balance = balance - ? WHERE phone = ?");
    $stmt->bind_param("ds", $fee, $user);
    $stmt->execute();

    // Commission
    addCommission($tng_conn, $user, $fee, $udata['parent'] ?? null, 'MOBILE TO PAN');

    // Wallet history
    $newBalance = $wallet - $fee;
    $stmt2 = $tng_conn->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, 'MOBILE TO PAN', '1', 'Debit')");
    $stmt2->bind_param("sds", $user, $fee, $newBalance);
    $stmt2->execute();

    $base64Json = base64_encode(json_encode($resdata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    $panNumber = $resdata['data']['pan_number'] ?? $resdata['pan'] ?? 'NA';

    $stmt3 = $tng_conn->prepare("INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) VALUES ('MOBILE_TO_PAN', ?, ?, ?, ?, NOW())");
    $stmt3->bind_param("ssss", $panNumber, $user, $mobile, $base64Json);
    $stmt3->execute();

    echo "<script>
        Swal.fire({
            icon:'success',
            title:'PAN FOUND',
            text:'Mobile to PAN data saved successfully',
            timer:2200,
            showConfirmButton:false
        }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<style>
body{
  background:linear-gradient(135deg,#fde2e4,#e0f2fe);
}
.glass{
  background:rgba(255,255,255,.97);
  border-radius:26px;
  box-shadow:0 28px 60px rgba(0,0,0,.15);
  padding:36px;
}
.back-btn{
  text-decoration:none;
  font-weight:600;
}
.title{
  font-weight:700;
  color:#7f1d1d;
}
</style>

<div class="page-wrapper">
<div class="page-content">
<div class="container">
<div class="row justify-content-center align-items-center" style="min-height:80vh;">
<div class="col-lg-5 col-md-7 col-sm-10">

<div class="glass">
<div class="mb-3">
  <a href="javascript:history.back()" class="back-btn text-danger">
    <i class="bi bi-arrow-left-circle"></i> Back
  </a>
</div>
<h4 class="title text-center mb-1">📱 Mobile + Name → PAN Lookup</h4>
<p class="text-muted text-center mb-4">Enter mobile number and name to find PAN</p>

<form method="post" id="mobilePanForm">
<div class="mb-3">
  <label class="fw-semibold">Mobile Number</label>
  <input type="text"
         name="mobileNumber"
         maxlength="10"
         minlength="10"
         class="form-control form-control-lg"
         placeholder="Enter 10 digit mobile number"
         required>
</div>

<div class="mb-3">
  <label class="fw-semibold">Full Name (as per PAN)</label>
  <input type="text"
         name="name"
         class="form-control form-control-lg"
         placeholder="Enter full name"
         required>
</div>

<div class="row mt-4 align-items-center">
  <div class="col-6">
    <input class="form-control fw-bold text-success"
           value="Fee ₹ <?= htmlspecialchars($fee) ?>" readonly>
  </div>
  <div class="col-6 text-end">
    <button type="submit" id="submitBtn" class="btn btn-danger px-4 rounded-pill">
      <i class="fa fa-search"></i> Find PAN
    </button>
  </div>
</div>
</form>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let lock = false;
document.getElementById('mobilePanForm').addEventListener('submit', function(e) {
    e.preventDefault();
    if (lock) return;

    Swal.fire({
        title: 'Confirm?',
        text: 'Proceed with Mobile + Name to PAN verification?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes',
        cancelButtonText: 'Cancel'
    }).then(result => {
        if (result.isConfirmed) {
            lock = true;
            document.getElementById('submitBtn').disabled = true;
            this.submit();
        }
    });
});
</script>

<?php include('../template/tngweb/footer.php'); ?>