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

$fee = $udata['family_Id_pvc_card_pdf_up_a'];
checkServiceStatus($udata, 'family_Id_pvc_card_pdf_up_a_status');

$appliedby = $udata['phone'];
$balance   = $udata['balance'];

/* ===============================
   FORM SUBMIT
================================ */
if (!empty($_POST['family_id'])) {

    $family_id = trim($_POST['family_id']);
    $debit_fee = $balance - $fee;

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

    $request = [
        'family_id' => $family_id
    ];

    $resdata = familyId_card_pdf_up_verification_api_run($request);

    if (!empty($resdata['error'])) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire('Error','".htmlspecialchars($resdata['error'])."','error');
        </script>";
    }
    elseif (($resdata['sampleCode'] ?? '') === "200") {

        date_default_timezone_set('Asia/Kolkata');
        $timestamp   = date("Y-m-d H:i:s");
        $parentPhone = $udata['parent'] ?? null;

  
        addCommission(
            $tng_conn,
            $appliedby,
            $fee,
            $parentPhone,
            "Family PVC Card PDF UP"
        );

    
        mysqli_query(
            $tng_conn,
            "UPDATE users SET balance = balance - $fee WHERE phone='$appliedby'"
        );

     
        mysqli_query(
            $tng_conn,
            "INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES
            (
                '$appliedby',
                '$fee',
                '$debit_fee',
                'Family PVC Card PDF UP',
                '1',
                'Debit'
            )"
        );

   
        mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES
            (
                'family_pvc_card_pdf_up',
                '".mysqli_real_escape_string($tng_conn,$resdata['name'])."',
                '$appliedby',
                '".mysqli_real_escape_string($tng_conn,$resdata['family_id'])."',
                '".mysqli_real_escape_string($tng_conn,$resdata['pdf'])."',
                '$timestamp'
            )"
        );


        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
        Swal.fire({
            icon:'success',
            title:'Success',
            text:'Family PVC Card PDF Generated Successfully',
            timer:1500,
            showConfirmButton:false
        }).then(()=>{
            window.location='all_history.php';
        });
        </script>";
    }
}
?>

<!-- ===============================
     LUXURY UI
================================ -->
<style>
.family-card{
    border-radius:18px;
    box-shadow:0 18px 40px rgba(0,0,0,.22);
    background:linear-gradient(135deg,#ffffff,#f4f7ff);
}
.family-title{
    background:linear-gradient(90deg,#141e30,#243b55);
    color:#fff;
    padding:12px;
    border-radius:12px;
    text-align:center;
    font-weight:600;
}
.family-btn{
    background:linear-gradient(45deg,#141e30,#243b55);
    border:none;
    border-radius:50px;
    padding:12px;
    color:#fff;
    font-weight:600;
}
.family-btn:hover{ transform:scale(1.05); }
</style>

<div class="content-wrap">
<div class="main">
<div class="page-wrapper">
<div class="page-content">
<div class="container-fluid">

<div class="row justify-content-center">
<div class="col-lg-4 col-md-6">

<div class="card family-card">
<div class="card-body">

<a href="javascript:history.back()" class="btn btn-light mb-3 w-100">
← Go Back
</a>

<div class="family-title mb-3">
Family PVC Card PDF – Uttar Pradesh
</div>

<form method="POST" id="familyForm">

<div class="mb-3">
<label class="fw-semibold">Enter Family Card Number</label>
<input type="text"
       name="family_id"
       class="form-control"
       required>
</div>

<div class="mb-3">
<input class="form-control text-center fw-bold"
       value="Fee ₹ <?php echo $fee; ?>" readonly>
</div>

<button type="submit"
        id="submitBtn"
        class="family-btn w-100">
Generate PDF
</button>

</form>

</div>
</div>

</div>
</div>

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

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

<!-- ===============================
     CONFIRM + DOUBLE SUBMIT SAFE
================================ -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {

let submitting = false;
const form = document.getElementById("familyForm");
const btn  = document.getElementById("submitBtn");

form.addEventListener("submit", function(e){
  e.preventDefault();
  if (submitting) return;

  Swal.fire({
    title:'Are you sure?',
    text:'PDF generate hogi aur wallet se fee deduct hogi',
    icon:'warning',
    showCancelButton:true,
    confirmButtonText:'Yes, Proceed',
    cancelButtonText:'Cancel'
  }).then((r)=>{
    if(r.isConfirmed){
      submitting = true;
      btn.disabled = true;
      btn.innerText = 'Processing...';
      form.submit();
    }
  });
});

});
</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>
</html>
