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

$fee = $udata['PinCode_To_Details_Find_a'];
checkServiceStatus($udata,'PinCode_To_Details_Find_a_status');

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

    $pincode = trim($_POST['pincode']);
    $user    = $udata['phone'];
    $wallet  = $udata['balance'];

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


    $resdata = pincode_verification_run([
        'pincode' => $pincode
    ]);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? 'Invalid Pincode';

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

  

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


    addCommission(
        $tng_conn,
        $user,
        $fee,
        $udata['parent'] ?? null,
        'PINCODE TO DETAILS'
    );


    mysqli_query(
        $tng_conn,
        "INSERT INTO wallethistory
        (userid,amount,balance,purpose,status,type)
        VALUES(
          '$user',
          '$fee',
          '".($wallet-$fee)."',
          'PINCODE TO DETAILS',
          '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(
          'PINCODE_TO_DETAILS',
          '$pincode',
          '$user',
          '$pincode',
          '".mysqli_real_escape_string($tng_conn,$base64Json)."',
          NOW()
        )"
    );

 
    echo "<script>
        Swal.fire({
            icon:'success',
            title:'PINCODE FOUND',
            text:'Pincode details fetched successfully',
            timer:2200,
            showConfirmButton:false
        });
    </script>";
}
?>

<!-- ================= LUXURY UI ================= -->
<style>
body{
  background:linear-gradient(135deg,#eef2ff,#fdf2f8);
}
.glass{
  background:#fff;
  border-radius:22px;
  box-shadow:0 25px 55px rgba(0,0,0,.14);
  padding:36px;
}
.title{
  font-weight:700;
  color:#1e40af;
}
.back-btn{
  font-weight:600;
  text-decoration:none;
}
</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-6 col-md-8 col-sm-12">

<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">
📮 PINCODE → DETAILS FINDER
</h4>

<p class="text-center text-muted mb-4">
Find Post Office & Area details using Pincode
</p>

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

<div class="mb-3">
    <label class="fw-semibold">Pincode</label>
    <input type="text"
           name="pincode"
           maxlength="6"
           class="form-control form-control-lg"
           placeholder="Enter 6 digit pincode"
           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> Fetch Details
        </button>
    </div>
</div>

</form>

</div>

<?php if (!empty($resdata['PostOffices']) && $sampleCode=="200"){ ?>
<div class="glass mt-4">
<h5 class="mb-3 text-center">📍 Pincode Details</h5>

<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>Name</th><th>Branch</th><th>Status</th><th>District</th><th>State</th><th>Country</th>
</tr>
</thead>
<tbody>
<?php foreach($resdata['PostOffices'] as $o){ ?>
<tr>
<td><?=htmlspecialchars($o['Name'])?></td>
<td><?=htmlspecialchars($o['BranchType'])?></td>
<td><?=htmlspecialchars($o['DeliveryStatus'])?></td>
<td><?=htmlspecialchars($o['District'])?></td>
<td><?=htmlspecialchars($o['State'])?></td>
<td><?=htmlspecialchars($o['Country'])?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?php } ?>

</div>
</div>

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

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

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

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