<?php
include('header.php');
$fee = 20;
$fee_res = mysqli_query($conn, "SELECT fee_amount FROM fee_settings WHERE service_name='aadhar_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 (isset($_POST['savedataauto'])) {
    if ($wallet < $fee) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";
        echo "<script>
            Swal.fire({ title: 'Low Wallet Balance!', text: 'Your wallet has ₹$wallet. Fee is ₹$fee. Please recharge.', icon: 'warning', confirmButtonText: 'OK' }).then((result) => { if (result.isConfirmed) { window.location.href = 'addwallet'; } });
        </script>";
        exit;
    }

    $aadharno = mysqli_real_escape_string($conn, trim($_POST['aadharno']));
    $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']));
    $birthtithilocal = mysqli_real_escape_string($conn, trim($_POST['birthtithilocal']));
    $gender = strtoupper(mysqli_real_escape_string($conn, trim($_POST['gender'])));
    $genderlocal = mysqli_real_escape_string($conn, trim($_POST['genderlocal']));
    $address = mysqli_real_escape_string($conn, trim($_POST['address']));
    $language = mysqli_real_escape_string($conn, trim($_POST['language']));
    $namelocal = mysqli_real_escape_string($conn, trim($_POST['namelocal']));
    $localaddress = mysqli_real_escape_string($conn, trim($_POST['addresslocal']));
    $patalocal = mysqli_real_escape_string($conn, trim($_POST['patalocal']));
    $houseno = mysqli_real_escape_string($conn, trim($_POST['houseno']));
    $street = mysqli_real_escape_string($conn, trim($_POST['streetlocality']));
    $pincode = mysqli_real_escape_string($conn, trim($_POST['pincode']));
    $vtcandpost = mysqli_real_escape_string($conn, trim($_POST['vtcandpost']));
    $dist = mysqli_real_escape_string($conn, trim($_POST['city']));
    $statename = mysqli_real_escape_string($conn, trim($_POST['state']));

    $image_base64 = '';
    if (isset($_FILES["imagefile"]) && $_FILES["imagefile"]["error"] == 0) {
        $image_info = getimagesize($_FILES["imagefile"]["tmp_name"]);
        $image_type = $image_info["mime"];
        $image_data = file_get_contents($_FILES["imagefile"]["tmp_name"]);
        $image_base64 = 'data:' . $image_type . ';base64,' . base64_encode($image_data);
    }

    if ($aadharno == "") {
        $msgno = 'Please Enter Aadhar Card No .... ';
    } elseif ($name == "") {
        $msgno = 'Please Enter Name .... ';
    } elseif ($fathername == "") {
        $msgno = 'Please Enter Father Name .... ';
    } elseif ($dobadhar == "") {
        $msgno = 'Please Enter Date of Birth .... ';
    } elseif ($gender == "") {
        $msgno = 'Please Enter Gender .... ';
    } elseif ($address == "") {
        $msgno = 'Please Enter Address .... ';
    } elseif ($language == "") {
        $msgno = 'Please Enter Local Language .... ';
    } elseif ($namelocal == "") {
        $msgno = 'Please Enter Name in Local Language .... ';
    } elseif ($localaddress == "") {
        $msgno = 'Please Enter Address in Local Language .... ';
    } else {
        $a = mysqli_query($conn, "SELECT aadharno FROM aadharauto WHERE aadharno='" . $aadharno . "'");
        $b = mysqli_fetch_array($a);

        if ($b && $b['aadharno'] == $aadharno) {
            $msgno = 'This Aadhar Card No Already Exist .... ';
        } else {
            $st = substr($aadharno, 0, 4);
            $nd = substr($aadharno, 4, 4);
            $rd = substr($aadharno, 8, 4);
            $adhrno = $st . ' ' . $nd . ' ' . $rd;

            $resultm = mysqli_query($conn, "SELECT srno FROM aadharauto ORDER BY srno DESC LIMIT 1");
            $num_rows = mysqli_fetch_array($resultm);
            $srno = ($num_rows ? $num_rows['srno'] + 1 : 1);

            $userid = $_SESSION['phone'];
            $image_base64_esc = mysqli_real_escape_string($conn, $image_base64);

            // Ensure UTF-8 charset before INSERT for Hindi/local language data
            mysqli_set_charset($conn, "utf8mb4");

            $query = "INSERT INTO `aadharauto`
                (`aadharno`, `originalaadharno`, `aadharname`, `fathername`, `dob`, `gender`, `sexinlocal`, `fulladdress`,
                `locallanguage`, `localname`, `localaddress`, `imagepathoriginal`, `dobinlocal`, `pata`, `houseno`, `street`, `vtcandpost`,
                `dist`, `statename`, `pincode`, `srno`, `userid`, `createdatetime`)
                VALUES (
                '$aadharno', '$adhrno', '$name', '$fathername', '$dobadhar', '$gender',
                '$genderlocal', '$address', '$language', '$namelocal', '$localaddress',
                '$image_base64_esc', '$birthtithilocal', '$patalocal', '$houseno', '$street',
                '$vtcandpost', '$dist', '$statename', '$pincode', '$srno', '$userid', NOW())";

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

            if ($result) {
                mysqli_query($conn, "UPDATE usertable SET walletamount=walletamount-$fee WHERE phone='$userid'");
                $_SESSION['walletamount'] = $_SESSION['walletamount'] - $fee;
                ?>
                <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                <script>
                    Swal.fire('Application Submitted Success', '', 'success');
                    setTimeout(() => { window.location = 'aadhar_advance_list'; }, 1500);
                </script>
                <?php
            } else {
                $msgno = "Error saving data: " . mysqli_error($conn);
            }
        }
    }
}

if (!empty($msgno)) {
    echo '<script>alert("' . $msgno . '");</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>
.aadhar-card {
    max-width: 950px;
    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;
}
.aadhar-header {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: #fff;
    padding: 20px 30px;
    display: flex;
    align-items: center;
    gap: 15px;
}
.aadhar-header i { font-size: 28px; }
.aadhar-header h4 { margin: 0; font-weight: 600; letter-spacing: 0.5px; }
.aadhar-body { padding: 30px; }
.section-title {
    color: #2a5298;
    font-weight: 700;
    margin-bottom: 18px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e2e8f0;
}
.form-group { margin-bottom: 18px; }
.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, .form-group textarea {
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    padding: 10px 14px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: #fff;
    width: 100%;
}
.form-group .form-control:focus, .form-group select:focus, .form-group textarea:focus {
    border-color: #2a5298;
    box-shadow: 0 0 0 3px rgba(42,82,152,0.15);
    outline: none;
}
.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; }
.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;
    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;
}
.btn-tools {
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: #fff;
    border: none;
    padding: 12px 25px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
}
.btn-tools:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(37,99,235,0.4); color: #fff; text-decoration: none; }
</style>

<div class="aadhar-card">
    <div class="aadhar-header">
        <i class="fas fa-address-card"></i>
        <div>
            <h4>Aadhaar Card Manual Apply</h4>
            <small style="opacity:0.8;">Fill the form below to generate Aadhaar card</small>
        </div>
    </div>
    <div class="aadhar-body">
        <form method="post" autocomplete="off" accept-charset="UTF-8" onSubmit="return validation();" enctype="multipart/form-data" action="">

            <!-- Section 1: Personal Details -->
            <h6 class="section-title"><i class="fas fa-user-edit"></i> Personal Details</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-id-card"></i> Aadhaar Card No.</label>
                        <div class="input-icon">
                            <input class="form-control" id="aadharno" autocomplete="off" name="aadharno" type="text" maxlength="12" required placeholder="Enter 12 digit Aadhaar No.">
                            <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="e.g. Raju Kumar">
                            <i class="fas fa-user"></i>
                        </div>
                    </div>
                </div>
                <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" placeholder="e.g. Shyam Singh" oninput="setaddress()">
                            <i class="fas fa-user-tie"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-venus-mars"></i> Gender</label>
                        <select class="form-control" name="gender" id="gender" required>
                            <option value="">-- Select Gender --</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </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_aadhar" type="text" required placeholder="Select DOB" readonly>
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <input id="birthtithi" name="birthtithi" type="hidden" value="Birth Tithi">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-camera"></i> Passport Photo</label>
                        <div class="upload-box">
                            <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>

            <!-- Section 2: Address Details -->
            <h6 class="section-title" style="margin-top:10px;"><i class="fas fa-map-marker-alt"></i> Address Details</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-home"></i> House No</label>
                        <input class="form-control" name="houseno" id="houseno" type="text" oninput="setaddress()" required placeholder="House No">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-road"></i> Gali, Locality</label>
                        <input class="form-control" name="streetlocality" id="streetlocality" oninput="setaddress()" type="text" required placeholder="Gali, Locality, Panchayat">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-envelope"></i> Post Office</label>
                        <input class="form-control" name="vtcandpost" id="vtcandpost" type="text" oninput="setaddress()" required placeholder="Post Office">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-city"></i> City / District</label>
                        <input class="form-control" name="city" id="city" type="text" oninput="setaddress()" required placeholder="City">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-flag"></i> State</label>
                        <input class="form-control" name="state" id="state" type="text" oninput="setaddress()" required placeholder="State">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-map-pin"></i> Pin Code</label>
                        <input class="form-control" name="pincode" id="pincode" type="text" maxlength="7" oninput="setaddress()" required placeholder="Pin Code">
                    </div>
                </div>
                <div class="col-12">
                    <div class="form-group">
                        <label><i class="fas fa-map-marked-alt"></i> Full Address</label>
                        <textarea class="form-control" placeholder="S/O : Name, House, Locality, Post, City, State, Pincode" style="height:60px" id="txtSource" name="address" rows="3"></textarea>
                        <span id="errortxtSource" class="text-danger" style="font-size:12px;"></span>
                    </div>
                </div>
            </div>

            <!-- Section 3: Local Language -->
            <h6 class="section-title" style="margin-top:10px;"><i class="fas fa-language"></i> Local Language Details</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-globe-asia"></i> Select Local Language</label>
                        <select class="form-control" onchange="changelang()" name="language" id="language" required>
                            <option value="">-- Select Language --</option>
                            <option value="HI">Hindi</option>
                            <option value="PA">Punjabi</option>
                            <option value="GU">Gujarati</option>
                            <option value="MR">Marathi</option>
                            <option value="TA">Tamil</option>
                            <option value="KN">Kannada</option>
                            <option value="BN">Bengali</option>
                            <option value="TE">Telugu</option>
                            <option value="OR">Oriya</option>
                            <option value="SD">Sindhi</option>
                        </select>
                        <span id="errorlanguage" 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-tag"></i> Name (Local Language)</label>
                        <input class="form-control" id="name_regional" name="namelocal" type="text" placeholder="Auto translate">
                        <span id="errorname_regional" class="text-danger" style="font-size:12px;"></span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-calendar"></i> DOB Local</label>
                        <input class="form-control" id="birthtithilocal" name="birthtithilocal" placeholder="Auto translate" type="text">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><i class="fas fa-venus-mars"></i> Gender Local</label>
                        <input class="form-control" id="genderlocal" name="genderlocal" type="text" placeholder="Auto translate">
                    </div>
                </div>
                <div class="col-12">
                    <div class="form-group">
                        <label><i class="fas fa-map-marked"></i> Address (Local Language)</label>
                        <textarea class="form-control" id="txtTarget" style="height:60px" name="addresslocal" rows="3" placeholder="Auto translate"></textarea>
                        <span id="errortxtTarget" class="text-danger" style="font-size:12px;"></span>
                    </div>
                </div>
            </div>

            <input id="pata" name="pata" type="hidden" value="address">
            <input id="patalocal" name="patalocal" type="hidden" value="">

            <!-- Wallet Balance -->
            <div class="row">
                <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>

                <!-- Fee & Submit -->
                <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>
                        <div style="display:flex; gap:10px; flex-wrap:wrap;">
                            <a href="https://www.google.com/intl/sa/inputtools/try/" target="_blank" class="btn-tools">
                                <i class="fas fa-keyboard"></i> Google Input Tools
                            </a>
                            <button type="submit" name="savedataauto" class="btn-submit">
                                <i class="fas fa-paper-plane"></i> Submit Application
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function validation() {
    var txtSource = document.getElementById('txtSource').value;
    if (txtSource.trim() == "") {
        document.getElementById('errortxtSource').innerHTML = " **Please Enter Address !!!";
        document.getElementById('txtSource').style.border = "1px solid red";
        document.getElementById('txtSource').focus();
        return false;
    }
    var name_regional = document.getElementById('name_regional').value;
    if (name_regional.trim() == "") {
        document.getElementById('errorname_regional').innerHTML = " **Please Enter Name in Local Language !!!";
        document.getElementById('name_regional').style.border = "1px solid red";
        document.getElementById('name_regional').focus();
        return false;
    }
    var txtTarget = document.getElementById('txtTarget').value;
    if (txtTarget.trim() == "") {
        document.getElementById('errortxtTarget').innerHTML = " **Please Enter Local Language Address !!!";
        document.getElementById('txtTarget').style.border = "1px solid red";
        document.getElementById('txtTarget').focus();
        return false;
    }
}

function setaddress() {
    var fathername = document.getElementById('fathername').value;
    var houseno = document.getElementById('houseno').value;
    var streetlocality = document.getElementById('streetlocality').value;
    var vtcandpost = document.getElementById('vtcandpost').value;
    var state = document.getElementById('state').value;
    var city = document.getElementById('city').value;
    var pincode = document.getElementById('pincode').value;
    document.getElementById('txtSource').innerHTML = "S/O : " + fathername + ", " + houseno + ", " + streetlocality + ", " + vtcandpost + ", " + city + ", " + state + ", " + pincode;
}

function changelang() {
    var lang = document.getElementById("language").value;
    var baseUrl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=EN&tl=" + lang + "&dt=t&q=";

    $.get(baseUrl + escape($("#txtSource").val()), function (data) {
        var result = '';
        for (var i = 0; i <= 500; i++) { if(data[0][i]) result += data[0][i][0]; else break; }
        $("#txtTarget").val(result);
    });

    $.get(baseUrl + escape($("#name").val()), function (data) {
        var result = '';
        for (var i = 0; i <= 500; i++) { if(data[0][i]) result += data[0][i][0]; else break; }
        $("#name_regional").val(result);
    });

    $.get(baseUrl + escape($("#gender").val()), function (data) {
        var result = '';
        for (var i = 0; i <= 500; i++) { if(data[0][i]) result += data[0][i][0]; else break; }
        if (result == "नर") result = "पुरुष";
        if (result == "ਨਰ") result = "ਮਰਦ";
        $("#genderlocal").val(result);
    });

    $.get(baseUrl + escape($("#birthtithi").val()), function (data) {
        var result = '';
        for (var i = 0; i <= 500; i++) { if(data[0][i]) result += data[0][i][0]; else break; }
        $("#birthtithilocal").val(result);
    });

    $.get(baseUrl + escape($("#pata").val()), function (data) {
        var result = '';
        for (var i = 0; i <= 500; i++) { if(data[0][i]) result += data[0][i][0]; else break; }
        $("#patalocal").val(result);
    });
}

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

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

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