<?php
include('header.php');
$fee = 10;
$fee_res = mysqli_query($conn, "SELECT fee_amount FROM fee_settings WHERE service_name='pan_print'");
if ($fee_res && mysqli_num_rows($fee_res) > 0) {
    $fee_row = mysqli_fetch_assoc($fee_res);
    $fee = $fee_row['fee_amount'];
}
$wallet = $_SESSION['walletamount'];

if ($wallet < $fee) {
?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    Swal.fire({ title: 'Low Balance!', text: 'Your wallet balance is low. Please recharge now.', icon: 'warning', confirmButtonText: 'Recharge Now' }).then(() => { window.location.href = "addwallet"; });
</script>
<?php
} elseif (isset($_POST['savedata'])) {
    $aadharno   = mysqli_real_escape_string($conn, trim($_POST['pannumber']));
    $name       = mysqli_real_escape_string($conn, trim($_POST['name']));
    $fathername = mysqli_real_escape_string($conn, trim($_POST['fathername']));
    $dobadhar   = mysqli_real_escape_string($conn, trim($_POST['dobadhar']));
    $gender     = mysqli_real_escape_string($conn, trim($_POST['gender']));

    $sign_image_type  = $_FILES["signfile"]["type"];
    $image_type       = $_FILES["imagefile"]["type"];
    $word = "image";

    if ($aadharno == "") {
        $msgno = 'Please Enter Pan Card No';
    } elseif ($name == "") {
        $msgno = 'Please Enter Name';
    } elseif ($fathername == "") {
        $msgno = 'Please Enter Father Name';
    } elseif ($dobadhar == "") {
        $msgno = 'Please Enter Date of Birth';
    } else {
        $a = mysqli_query($conn, "SELECT panno FROM panauto WHERE panno='" . $aadharno . "'");
        $b = mysqli_fetch_array($a);

        if ($b && $b['panno'] == $aadharno) {
            $msgno = 'This Pan Card No Already Exist';
        } else {
            if ((strpos($sign_image_type, $word) !== false) && (strpos($image_type, $word) !== false)) {
                $image_base64 = "data:" . $image_type . ";base64," . base64_encode(file_get_contents($_FILES['imagefile']['tmp_name']));
                $sign_base64  = "data:" . $sign_image_type . ";base64," . base64_encode(file_get_contents($_FILES['signfile']['tmp_name']));

                date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
                $userid = $_SESSION['phone'];

                $query = "INSERT INTO panauto(`userid`,`panno`,`name`,`fathername`,`dob`,`gender`,`image`,`signimage`,`create_time`)
                          VALUES('" . $userid . "','" . $aadharno . "','" . $name . "','" . $fathername . "','" . $dobadhar . "','" . $gender . "','" . mysqli_real_escape_string($conn, $image_base64) . "','" . mysqli_real_escape_string($conn, $sign_base64) . "','" . $timestamp . "')";

                $result = mysqli_query($conn, $query);

                if ($result) {
                    mysqli_query($conn, "UPDATE usertable SET walletamount=walletamount-$fee WHERE phone='$userid'");
                    $_SESSION['walletamount'] = $_SESSION['walletamount'] - $fee;
                    $_SESSION["Panno"] = trim($aadharno);

                    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                    <script>
                        Swal.fire({ title: "Success!", text: "Pan Card submitted successfully", icon: "success", timer: 1500, showConfirmButton: false });
                        setTimeout(function () { window.location = "Pan_manual_list"; }, 1500);
                    </script>';
                }
            } else {
                $msgno = "Please select PNG or JPEG image only";
            }
        }
    }
}

if (!empty($msgno)) {
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';
    echo '<script>Swal.fire({ title: "Error!", text: "' . $msgno . '", icon: "error" });</script>';
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<style>
.pan-card {
    max-width: 900px;
    margin: 25px auto;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9ff 100%);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0,0,0,0.12);
    overflow: hidden;
}
.pan-header {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: #fff;
    padding: 20px 30px;
    display: flex;
    align-items: center;
    gap: 15px;
}
.pan-header i { font-size: 28px; }
.pan-header h4 { margin: 0; font-weight: 600; letter-spacing: 0.5px; }
.pan-body { padding: 30px; }
.form-group { margin-bottom: 20px; }
.form-group label {
    font-weight: 600;
    color: #344767;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 6px;
    display: block;
}
.form-group .form-control, .form-group select {
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    padding: 10px 14px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: #fff;
}
.form-group .form-control:focus, .form-group select:focus {
    border-color: #2a5298;
    box-shadow: 0 0 0 3px rgba(42,82,152,0.15);
    outline: none;
}
.upload-box {
    border: 2px dashed #cbd5e1;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    background: #f8fafc;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
}
.upload-box:hover { border-color: #2a5298; background: #eff6ff; }
.upload-box i { font-size: 32px; color: #94a3b8; margin-bottom: 8px; }
.upload-box p { margin: 0; color: #64748b; font-size: 13px; }
.upload-box input[type="file"] {
    position: absolute; top: 0; left: 0; width: 100%; height: 100%;
    opacity: 0; cursor: pointer;
}
.upload-box img {
    margin-top: 10px;
    border-radius: 8px;
    border: 2px solid #e2e8f0;
    display: none;
}
.fee-badge {
    background: linear-gradient(135deg, #ff9a00 0%, #ff6b00 100%);
    color: #fff;
    padding: 10px 20px;
    border-radius: 10px;
    font-weight: 700;
    font-size: 16px;
    display: inline-block;
}
.btn-submit {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: #fff;
    border: none;
    padding: 12px 40px;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 0.5px;
    cursor: pointer;
    transition: all 0.3s ease;
}
.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(30,60,114,0.4);
    color: #fff;
}
.input-icon {
    position: relative;
}
.input-icon i {
    position: absolute; right: 14px; top: 50%; transform: translateY(-50%);
    color: #94a3b8; pointer-events: none;
}
.input-icon .form-control { padding-right: 40px; }
</style>

<div class="pan-card">
    <div class="pan-header">
        <i class="fas fa-id-card"></i>
        <div>
            <h4>PAN Card Manual Apply</h4>
            <small style="opacity:0.8;">Fill the form below to generate PAN card</small>
        </div>
    </div>
    <div class="pan-body">
        <form method="post" autocomplete="off" onSubmit="return validation();" enctype="multipart/form-data" action="">
            <div class="row">
                <!-- Row 1: Pan Card Type | Gender -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-list-alt"></i> Pan Card Type</label>
                        <select name="ptype" id="ptype" class="form-control" 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)</option>
                            <option value="NSDL-MINOR">NSDL MINOR (Below 18)</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-venus-mars"></i> Gender</label>
                        <select name="gender" class="form-control" required>
                            <option value="">-- Select --</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                </div>

                <!-- Row 2: Pan Card No | Full Name -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-credit-card"></i> Pan Card No.</label>
                        <div class="input-icon">
                            <input class="form-control" id="pannumber" name="pannumber" type="text" maxlength="10" required placeholder="e.g. ABCDE1234F" onkeyup="this.value = this.value.toUpperCase();" onblur="ValidatePAN()">
                            <i class="fas fa-id-badge"></i>
                        </div>
                        <span id="erroraadharno" class="text-danger" style="font-size:12px;"></span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Full Name</label>
                        <div class="input-icon">
                            <input class="form-control" id="name" name="name" type="text" required placeholder="Enter full name" onkeyup="this.value = this.value.toUpperCase();">
                            <i class="fas fa-user"></i>
                        </div>
                    </div>
                </div>

                <!-- Row 3: Father's Name | Date of Birth -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-user-tie"></i> Father's Name</label>
                        <div class="input-icon">
                            <input class="form-control" name="fathername" id="fathername" type="text" required placeholder="Enter father's name" onkeyup="this.value = this.value.toUpperCase();">
                            <i class="fas fa-user-tie"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-calendar-alt"></i> Date of Birth</label>
                        <div class="input-icon">
                            <input class="form-control" name="dobadhar" id="dobpicker" type="text" required placeholder="Select DOB" readonly>
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                    </div>
                </div>

                <!-- Row 4: Passport Photo | Signature -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label id="stype"><i class="fas fa-camera"></i> Passport Photo</label>
                        <div class="upload-box" id="photoBox">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p>Click to upload photo<br><small>PNG, JPG (Max 2MB)</small></p>
                            <input type="file" name="imagefile" id="imgInp" accept="image/png,image/jpeg" required />
                            <img src="" id="blah" width="90" height="90" />
                        </div>
                    </div>
                </div>
                <div class="col-md-6" id="signBox">
                    <div class="form-group">
                        <label id="simgs"><i class="fas fa-signature"></i> Signature</label>
                        <div class="upload-box">
                            <i class="fas fa-file-signature"></i>
                            <p>Click to upload signature<br><small>PNG, JPG (Max 2MB)</small></p>
                            <input type="file" name="signfile" id="signInp" accept="image/png,image/jpeg" required />
                            <img src="" id="blahs" width="120" height="50" />
                        </div>
                    </div>
                </div>

                <!-- News / Notice -->
                <div class="col-12">
                    <div style="background:linear-gradient(135deg,#ebf5ff 0%,#e0f2fe 100%); border:2px solid #3b82f6; border-radius:10px; padding:14px 18px; margin-top:5px;">
                        <p style="margin:0; color:#1e40af; font-weight:700; font-size:14px;"><i class="fas fa-bullhorn"></i> Important Notice</p>
                        <ul style="margin:8px 0 0 0; padding-left:20px; color:#1e3a5f; font-size:13px; line-height:1.8;">
                            <li>Signature ko <b>PNG format</b> me upload kare, PAN Card me signature achha aayega.</li>
                            <li>Signature ka background remove karne ke liye yahan click kare: <a href="https://www.remove.bg/" target="_blank" style="color:#2563eb; font-weight:700; text-decoration:underline;"><i class="fas fa-external-link-alt"></i> Remove.bg</a></li>
                        </ul>
                    </div>
                </div>

                <!-- Row 5: Wallet Balance (Full Width) -->
                <div class="col-12">
                    <div style="background:#fffbeb; border:2px solid #fbbf24; border-radius:10px; padding:12px; margin-top:5px; text-align:center;">
                        <small style="color:#92400e; font-weight:600;">WALLET BALANCE</small>
                        <h5 style="color:#047857; margin:4px 0; font-weight:800;">&#8377;<?php echo $_SESSION['walletamount']; ?></h5>
                    </div>
                </div>

                <!-- Row 6: Fee & Submit (Full Width) -->
                <div class="col-12" style="margin-top:15px;">
                    <hr style="border-color:#e2e8f0;">
                    <div class="d-flex justify-content-between align-items-center flex-wrap" style="gap:15px;">
                        <div class="fee-badge">
                            <i class="fas fa-wallet"></i> Application Fee: &#8377;<?php echo $fee; ?>
                        </div>
                        <button type="submit" name="savedata" class="btn-submit">
                            <i class="fas fa-paper-plane"></i> Submit Application
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
// Date Picker
flatpickr("#dobpicker", {
    dateFormat: "d/m/Y",
    maxDate: "today",
    allowInput: false,
    disableMobile: true
});

// Validation
function validation() {
    var pan = document.getElementById('pannumber').value;
    if (pan.length < 10) {
        document.getElementById('erroraadharno').innerHTML = "Please Enter 10 Digit Pan Card Number";
        document.getElementById('pannumber').style.border = "2px solid red";
        document.getElementById('pannumber').focus();
        return false;
    }
    return true;
}

function ValidatePAN() {
    var pan_no = document.getElementById("pannumber");
    if (pan_no.value != "") {
        var panPattern = /^([a-zA-Z]{5})(\d{4})([a-zA-Z]{1})$/;
        if (pan_no.value.search(panPattern) == -1) {
            Swal.fire({ title: 'Invalid PAN', text: 'Please enter a valid PAN number (e.g. ABCDE1234F)', icon: 'error' });
            pan_no.value = '';
            return false;
        }
    }
}

// Photo preview
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) { $('#blah').attr('src', e.target.result).show(); }
        reader.readAsDataURL(input.files[0]);
    }
}
$("#imgInp").change(function(){ readURL(this); });

// Signature preview
function readURLs(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) { $('#blahs').attr('src', e.target.result).show(); }
        reader.readAsDataURL(input.files[0]);
    }
}
$("#signInp").change(function(){ readURLs(this); });

// Hide signature for MINOR type
$("#ptype").on('change', function() {
    if ($(this).val() == 'UTI-MINOR' || $(this).val() == 'NSDL-MINOR') {
        $("#signBox").hide();
        $("#signInp").removeAttr('required');
    } else {
        $("#signBox").show();
        $("#signInp").attr('required', 'required');
    }
});
</script>

<script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="dist/js/adminlte.js"></script>
</body>
</html>
