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

$fee = $udata['pan_manual_fee'];
checkServiceStatus($udata, 'pan_manual_fee_status');
 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $aadharno   = strtoupper(trim($_POST['pannumber']));
    $name       = strtoupper(trim($_POST['name']));
    $fathername = strtoupper(trim($_POST['fathername']));
    $dobadhar   = trim($_POST['dobadhar']);
    $gender     = trim($_POST['gender']);
    $ptype      = trim($_POST['ptype']);
    $appliedby  = $udata['phone'];
    $debit_fee  = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {

        // Check duplicate PAN
        $check = mysqli_query($tng_conn, "SELECT * FROM all_pdf_records WHERE number='$aadharno' AND service_name='PAN_MANUAL'");
        if(mysqli_num_rows($check) > 0) {
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire('Error', 'This PAN Number Already Exists!', 'error');
            </script>";
        } else {
            
            // Process Photo (convert to base64)
            $image_tmp = $_FILES['imagefile']['tmp_name'];
            $image_type = $_FILES['imagefile']['type'];
            $image_content = file_get_contents($image_tmp);
            $image_base64 = "data:" . $image_type . ";base64," . base64_encode($image_content);
            
            // Process Signature (if exists)
            $sign_base64 = '';
            if(isset($_FILES['signfile']) && $_FILES['signfile']['error'] == 0) {
                $sign_tmp = $_FILES['signfile']['tmp_name'];
                $sign_type = $_FILES['signfile']['type'];
                $sign_content = file_get_contents($sign_tmp);
                $sign_base64 = "data:" . $sign_type . ";base64," . base64_encode($sign_content);
            }
            
            date_default_timezone_set('Asia/Kolkata');
            $timestamp = date("Y-m-d H:i:s");
            
            // Create data array (SAME LIKE vehicle_rc pattern)
            $resdata = [
                'fullname' => $name,
                'fathername' => $fathername,
                'rcno' => $aadharno,
                'dob' => $dobadhar,
                'gender' => $gender,
                'ptype' => $ptype,
                'image' => $image_base64,
                'signimage' => $sign_base64
            ];
            
            /* Commission */
            $parentPhone = $udata['parent'] ?? null;
            addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Pan Manual Verification");
            
            /* Balance Deduct */
            mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$appliedby'");
            
            /* Wallet History */
            mysqli_query($tng_conn, "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type)
                VALUES ('$appliedby','$fee','$debit_fee','Pan Manual Verification','1','Debit')");
            
            /* ✅ MAIN INSERT - SAME LIKE vehicle_rc */
            mysqli_query($tng_conn, "INSERT INTO all_pdf_records
                (service_name, name, username, number, pdf, date)
                VALUES
                (
                    'PAN_MANUAL',
                    '" . mysqli_real_escape_string($tng_conn, $resdata['fullname']) . "',
                    '" . $udata['phone'] . "',
                    '" . mysqli_real_escape_string($tng_conn, $resdata['rcno']) . "',
                    '" . mysqli_real_escape_string($tng_conn, base64_encode(json_encode($resdata))) . "',
                    '$timestamp'
                )");
            
            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon:'success',
                    title:'Success',
                    text:'PAN Card Submitted Successfully',
                    timer:1500,
                    showConfirmButton:false
                }).then(()=>{ window.location='all_history.php'; });
            </script>";
        }
    } else {
        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>";
    }
}
?>

<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;
}
.preview-img {
    margin-top: 12px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    max-width: 100px;
    max-height: 100px;
    object-fit: cover;
    display: block;
}
</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;">🪪 PAN Card Registration</h5>
    <p class="text-muted small">Enter your details for PAN Card</p>
</div>

<form method="post" enctype="multipart/form-data" id="panForm">

<div class="mb-3">
    <label class="form-label">PAN CARD TYPE *</label>
    <select name="ptype" id="ptype" class="form-select" style="border-radius: 12px; padding: 12px;" required>
        <option value="UTI-NONMINOR">UTI NONMINOR (18+ years)</option>
        <option value="NSDL-NONMINOR">NSDL NONMINOR (18+ years)</option>
        <option value="UTI-MINOR">UTI MINOR (Below 18 years)</option>
        <option value="NSDL-MINOR">NSDL MINOR (Below 18 years)</option>
    </select>
</div>

<div class="mb-3">
    <label class="form-label">PAN CARD NUMBER *</label>
    <input type="text" name="pannumber" id="pannumber" class="form-control"
           placeholder="Enter 10 Digit PAN Number" maxlength="10"
           style="border-radius: 12px; padding: 12px;" 
           onkeyup="this.value = this.value.toUpperCase();" required>
</div>

<div class="mb-3">
    <label class="form-label">FULL NAME *</label>
    <input type="text" name="name" class="form-control"
           placeholder="Enter Full Name" 
           style="border-radius: 12px; padding: 12px;" 
           onkeyup="this.value = this.value.toUpperCase();" required>
</div>

<div class="mb-3">
    <label class="form-label">FATHER'S NAME *</label>
    <input type="text" name="fathername" class="form-control"
           placeholder="Enter Father's Name" 
           style="border-radius: 12px; padding: 12px;" 
           onkeyup="this.value = this.value.toUpperCase();" required>
</div>

<div class="row">
    <div class="col-md-6 mb-3">
        <label class="form-label">DATE OF BIRTH *</label>
        <input type="text" name="dobadhar" class="form-control"
               placeholder="DD/MM/YYYY" 
               style="border-radius: 12px; padding: 12px;" required>
    </div>
    
    <div class="col-md-6 mb-3">
        <label class="form-label">GENDER *</label>
        <select name="gender" class="form-select" style="border-radius: 12px; padding: 12px;" required>
            <option value="">Select</option>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
            <option value="Other">Other</option>
        </select>
    </div>
</div>

<div class="row">
    <div class="col-md-6 mb-3">
        <label class="form-label">PHOTO *</label>
        <input type="file" name="imagefile" id="imgInp" class="form-control" 
               style="border-radius: 12px; padding: 8px;" accept="image/*" required>
        <img id="blah" class="preview-img" style="display: none;">
    </div>
    
    <div class="col-md-6 mb-3" id="signDiv">
        <label class="form-label" id="simgs">SIGNATURE *</label>
        <input type="file" name="signfile" id="signInp" class="form-control" 
               style="border-radius: 12px; padding: 8px;" accept="image/*">
        <img id="blahs" class="preview-img" style="display: none;">
    </div>
</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;">💰 APPLICATION FEE</span>
    <span class="fw-bold fs-5" style="color: #1e293b;">₹ <?= number_format($fee, 2) ?></span>
</div>

<button type="submit" name="savedata" class="btn btn-success w-100 py-2" id="submitBtn" 
        style="border-radius: 12px; font-weight: 600; font-size: 16px;">
    📄 SUBMIT PAN CARD
</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 src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
    $("#ptype").on('change', function() {
        if($(this).val() == 'UTI-MINOR' || $(this).val() == 'NSDL-MINOR') {
            $("#signInp").prop('required', false);
            $("#signDiv").hide();
        } else {
            $("#signInp").prop('required', true);
            $("#signDiv").show();
        }
    });
    $("#ptype").trigger('change');
});

function readURL(input, imgElement) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) { $(imgElement).attr('src', e.target.result).show(); }
        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function() { readURL(this, "#blah"); });
$("#signInp").change(function() { readURL(this, "#blahs"); });

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

    var pan = document.getElementById("pannumber").value;
    var panPattern = /^([A-Z]{5})(\d{4})([A-Z]{1})$/;
    if(pan && !panPattern.test(pan)) {
        Swal.fire('Invalid PAN', 'Example: ABCDE1234F', 'error');
        return;
    }

    Swal.fire({
        title: 'Confirm Submission?',
        text: 'PAN Card generate hoga aur wallet se fee deduct hogi',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Proceed',
        cancelButtonText: 'Cancel'
    }).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>