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

$fee = $udata['gst_to_pan_fee'];
checkServiceStatus($udata,'gst_to_pan_fee_status');

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

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

    if ($balance < $fee) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire('Low Balance', 'Please recharge wallet', 'error')
            .then(()=>window.location='wallet.php');
        </script>";
    } else {

        $resdata = gst_to_pan_verification_api_run(['gstin'=>$gstin]);
        $sampleCode = $resdata['sampleCode'] ?? '';
        $error = $resdata['error'] ?? '';

        if ($sampleCode !== "200") {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire('Failed', '".addslashes($error ?: 'Invalid GST / API Error')."', 'error');
            </script>";
        } else {

            $parent = $udata['parent'] ?? null;

            mysqli_query($tng_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$user'");
            addCommission($tng_conn, $user, $fee, $parent, 'GST TO PAN');
            mysqli_query($tng_conn, "INSERT INTO wallethistory(userid,amount,balance,purpose,status,type)
                VALUES('$user', '$fee', '".($balance-$fee)."', 'GST TO PAN', '1', 'Debit')");

            $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(
                    'GST_TO_PAN',
                    '".mysqli_real_escape_string($tng_conn, $resdata['fullname'] ?? 'GST Holder')."',
                    '$user',
                    '".mysqli_real_escape_string($tng_conn, $gstin)."',
                    '".mysqli_real_escape_string($tng_conn, $base64Json)."',
                    NOW()
                )");

            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon:'success',
                    title:'Success!',
                    text:'PAN details fetched successfully',
                    timer:2000,
                    showConfirmButton:false
                }).then(()=>window.location='all_history.php');
            </script>";
        }
    }
}
?>

<style>
.card-shine {
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    transition: .3s;
    border: none;
}
.card-shine:hover {
    transform: translateY(-3px);
    box-shadow: 0 18px 40px rgba(0,0,0,0.15);
}
.container-center {
    min-height: 85vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
}
.form-label {
    font-weight: 600;
    font-size: 13px;
    margin-bottom: 6px;
    color: #333;
}
.single-line {
    width: 100%;
    height: 1px;
    background: linear-gradient(90deg, transparent, #e2e8f0, #e2e8f0, #e2e8f0, transparent);
    margin: 20px 0;
}
</style>

<div class="content-wrap">
<div class="main">
<div class="page-wrapper">
<div class="container-center">
<div class="page-content w-100 d-flex justify-content-center">

<div class="col-lg-5 col-md-7 col-sm-10">
<div class="card card-shine">
<div class="card-body p-4">

<a href="javascript:history.back()" class="btn btn-light mb-4 w-100 py-2" style="border-radius: 12px;">
    ← Go Back
</a>

<div class="text-center mb-4">
    <h5 class="fw-bold mb-1" style="color: #1e293b;">🏢 GST to PAN Finder</h5>
    <p class="text-muted small">Verify PAN details using GST Number</p>
</div>

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

<div class="mb-3">
    <label class="form-label">GST NUMBER *</label>
    <input type="text" name="inputGST" id="gstin" class="form-control"
           placeholder="Enter 15-digit GSTIN Number" 
           style="border-radius: 12px; padding: 12px;" 
           onkeyup="this.value = this.value.toUpperCase();" required>
    <small class="text-muted">Example: 22AAAAA0000A1Z</small>
</div>

<div class="single-line"></div>

<div class="d-flex justify-content-between align-items-center mb-4">
    <span class="fw-semibold" style="color: #475569;">💰 SERVICE CHARGE</span>
    <span class="fw-bold fs-5" style="color: #1e293b;">₹ <?= number_format($fee, 2) ?></span>
</div>

<button type="submit" class="btn btn-primary w-100 py-2" id="submitBtn" 
        style="border-radius: 12px; font-weight: 600; font-size: 16px;">
    🔍 VERIFY & FETCH
</button>

</form>

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

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

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// GSTIN Validation (15 characters)
function validateGSTIN(gstin) {
    var gstinPattern = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/;
    return gstinPattern.test(gstin);
}

let submitting = false;
document.getElementById("gstForm").addEventListener("submit", function(e) {
    e.preventDefault();
    if (submitting) return;

    var gstin = document.getElementById("gstin").value;
    if(!validateGSTIN(gstin)) {
        Swal.fire('Invalid GSTIN', 'Please enter valid 15-digit GSTIN number', 'error');
        return;
    }

    Swal.fire({
        title: 'Confirm?',
        text: 'GST to PAN verification hoga aur wallet se fee deduct hogi',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Proceed',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#3085d6'
    }).then((result) => {
        if (result.isConfirmed) {
            submitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerText = 'Processing...';
            this.submit();
        }
    });
});
</script>

<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
</html>