<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/Adhar_manual.php');

// Service Price
$priceQuery = mysqli_query($ahk_conn, "SELECT `price` FROM `pricing` WHERE `service_name`='aadhar_manual' LIMIT 1");
$priceData = mysqli_fetch_assoc($priceQuery);
$fee = $priceData['price'] ?? 20; 
 $wallet_amount = $udata['balance'];

// ------------ AUTO SAVE DATA -----------------
if (isset($_POST['savedataauto'])) {
    $q = "SELECT * FROM users where phone='".$_SESSION['phone']."'";
    $r = mysqli_query($ahk_conn,$q);
    $rw = mysqli_fetch_assoc($r);
    if($wallet_amount < $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_amount. Fee is ₹$fee. Please recharge.',
            icon: 'warning',
            confirmButtonText: 'OK'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'wallet.php';
            }
        });
    </script>
    ";
    exit;
    }
    $aadharno = trim($_POST['aadharno']);
    $name = trim($_POST['name']);
    $fathername = trim($_POST['fathername']);
    $dobadhar = trim($_POST['dobadhar']);
    $birthtithilocal = trim($_POST['birthtithilocal']);
    $gender = strtoupper(trim($_POST['gender']));
    $genderlocal = trim($_POST['genderlocal']);
    $address = trim($_POST['address']);
    $language = trim($_POST['language']);
    $namelocal = trim($_POST['namelocal']);
    $localaddress = trim($_POST['addresslocal']);
    $patalocal = trim($_POST['patalocal']);
    $houseno = trim($_POST['houseno']);
    $street = trim($_POST['street']);
    $pincode = trim($_POST['pincode']);
    $vtcandpost = trim($_POST['vtcandpost']);
    $dist = trim($_POST['dist']);
    $statename = trim($_POST['statename']);
    
    // Process image as base64
    $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 .... ';
    } else if ($rw['aadharpoint'] > $rw['balance']) {
        $msgno = "Sorry, Your Balance is Low .... Please Recharge Soon";
        ?>
        <script>
        setTimeout(function () {
            window.location.href = 'Adhar_manual.php';
        }, 2000);
        </script>
        <?php	
    } 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($ahk_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;
            
            $sex = ($gender == 'Male') ? 'M' : 'F';
            
            // Get next serial number
            $resultm = mysqli_query($ahk_conn, "SELECT srno FROM aadharauto ORDER BY srno DESC LIMIT 1");
            $num_rows = mysqli_fetch_array($resultm);
            $srno = $num_rows['srno'] + 1;
            
            // Insert Query
            $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 (
                '" . mysqli_real_escape_string($ahk_conn, $aadharno) . "',
                '" . mysqli_real_escape_string($ahk_conn, $adhrno) . "',
                '" . mysqli_real_escape_string($ahk_conn, $name) . "',
                '" . mysqli_real_escape_string($ahk_conn, $fathername) . "',
                '" . mysqli_real_escape_string($ahk_conn, $dobadhar) . "',
                '" . mysqli_real_escape_string($ahk_conn, $gender) . "',
                N'" . mysqli_real_escape_string($ahk_conn, $genderlocal) . "',
                '" . mysqli_real_escape_string($ahk_conn, $address) . "',
                '" . mysqli_real_escape_string($ahk_conn, $language) . "',
                N'" . mysqli_real_escape_string($ahk_conn, $namelocal) . "',
                N'" . mysqli_real_escape_string($ahk_conn, $localaddress) . "',
                '" . mysqli_real_escape_string($ahk_conn, $image_base64) . "',
                N'" . mysqli_real_escape_string($ahk_conn, $birthtithilocal) . "',
                N'" . mysqli_real_escape_string($ahk_conn, $patalocal) . "',
                '" . mysqli_real_escape_string($ahk_conn, $houseno) . "',
                '" . mysqli_real_escape_string($ahk_conn, $street) . "',
                '" . mysqli_real_escape_string($ahk_conn, $vtcandpost) . "',
                '" . mysqli_real_escape_string($ahk_conn, $dist) . "',
                '" . mysqli_real_escape_string($ahk_conn, $statename) . "',
                '" . mysqli_real_escape_string($ahk_conn, $pincode) . "',
                '$srno',
                '" . mysqli_real_escape_string($ahk_conn, $_SESSION['phone']) . "',
                NOW()
                )";
            
            $result = mysqli_query($ahk_conn, $query);
            
            if ($result) {
                $debit_fee = $udata['balance'] - $fee;
                $parentPhone = $udata['parent'] ?? null;
                $appliedby = $udata['phone'] ?? null;
        addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Aadhar Manual Verification");
                $debit = mysqli_query($ahk_conn, "UPDATE users SET balance=balance-$fee WHERE phone='{$_SESSION['phone']}'");
                $updatehistory = mysqli_query($ahk_conn, "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('{$_SESSION['phone']}','$fee','$debit_fee','Aadhar Manual  print','1','Debit')");
       
                $msg = "Please Wait Aadhar Preview just a second...";
                $_SESSION["IMGPATH"] = '';
                $_SESSION["AADHAARNO"] = trim($aadharno);
                
               
                
                ?>
                <script>
                    $(function(){
                        Swal.fire(
                            'Application Submitted Success',
                            '',
                            'success'
                        )
                    })
                    setTimeout(() => {
                        window.location='aadhar_advance_list.php';
                    }, 1500);
                </script>
                <?php
            } else {
                $msgno = "Error saving data: " . mysqli_error($ahk_conn);
            }
        }
    }
}
?>