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

$fee = $udata['gstin_2_contact'];
checkServiceStatus($udata,'gstin_2_contact_status');

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

    $gstin   = strtoupper(trim($_POST['gstin']));
    $user    = $udata['phone'];
    $balance = $udata['balance'];

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

    // API CALL
    $resdata = gst_to_contact_verification_api_run([
        'gstin'=>$gstin
    ]);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $error      = $resdata['error'] ?? '';

    // ❌ ERROR CASE
    if ($sampleCode !== "200") {
        echo "<script>
          Swal.fire(
            'Failed',
            '".addslashes($error ?: 'Invalid GSTIN or API error')."',
            'error'
          );
        </script>";
        exit;
    }

    /* ✅ SUCCESS CASE */

    // WALLET DEBIT
    mysqli_query(
        $tng_conn,
        "UPDATE users SET balance=balance-$fee WHERE phone='$user'"
    );

    // COMMISSION
    addCommission(
        $tng_conn,
        $user,
        $fee,
        $udata['parent'] ?? null,
        'GSTIN TO CONTACT'
    );

    // WALLET HISTORY
    mysqli_query(
        $tng_conn,
        "INSERT INTO wallethistory(userid,amount,balance,purpose,status,type)
         VALUES(
            '$user',
            '$fee',
            '".($balance-$fee)."',
            'GSTIN TO CONTACT',
            '1',
            'Debit'
         )"
    );

    // SAVE FULL API JSON (BASE64)
    $base64Json = base64_encode(
        json_encode($resdata,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)
    );

    mysqli_query(
        $tng_conn,
        "INSERT INTO all_pdf_records
         (service_name,name,username,number,pdf,date)
         VALUES(
            'GSTIN_TO_CONTACT',
            '$gstin',
            '$user',
            '$gstin',
            '".mysqli_real_escape_string($tng_conn,$base64Json)."',
            NOW()
         )"
    );

    // SUCCESS
    echo "<script>
      Swal.fire({
        icon:'success',
        title:'Contact Found',
        text:'GSTIN contact details saved successfully',
        timer:2200,
        showConfirmButton:false
      }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<!-- ================== LUXURY UI ================== -->
<style>
body{
  background:linear-gradient(135deg,#eef2ff,#f9fafb);
}
.glass{
  background:rgba(255,255,255,.96);
  backdrop-filter:blur(18px);
  border-radius:22px;
  box-shadow:0 25px 50px rgba(0,0,0,.12);
  padding:32px;
}
.title{
  font-weight:700;
  color:#4338ca;
}
.back-btn{
  text-decoration:none;
  font-weight:600;
}
</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-primary">
    <i class="bi bi-arrow-left-circle"></i> Back
  </a>
</div>

<h4 class="title text-center mb-2">
📞 GSTIN to Contact Finder
</h4>

<p class="text-muted text-center mb-4">
Find registered mobile & email using GSTIN (All India)
</p>

<form method="post" id="gstContactForm">

<div class="mb-3">
  <label class="fw-semibold">GSTIN</label>
  <input type="text"
         name="gstin"
         class="form-control form-control-lg"
         placeholder="Enter GSTIN"
         required>
</div>

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

</form>

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

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

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

  Swal.fire({
    title:'Confirm?',
    text:'Proceed to fetch GSTIN contact details?',
    icon:'question',
    showCancelButton:true,
    confirmButtonText:'Yes',
    cancelButtonText:'Cancel'
  }).then(res=>{
    if(res.isConfirmed){
      locked=true;
      document.getElementById('submitBtn').disabled=true;
      this.submit();
    }
  });
});
</script>

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