<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
$fee    = $udata['tng_aadhar_advance_ekyc_fee'] ?? 20;
checkServiceStatus($udata, 'tng_aadhar_advance_ekyc_fee_status');
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['move_to_otp'])) {
        
        $_SESSION['ekyc_data'] = [
            'aadhar' => $_POST['aadhar'],
            'bioenc' => $_POST['bioenc'],
            'biometric_data' => $_POST['bioenc']
        ];
        $current_step = 'otp';
    }
    elseif (isset($_POST['send_otp'])) {
        
        $mobileNumber = $_POST['mobileNumber'];
        $aadhar = $_SESSION['ekyc_data']['aadhar'] ?? $_POST['aadhar'];
        $bioenc = $_SESSION['ekyc_data']['biometric_data'] ?? $_POST['bioenc'];
        
        
        $_SESSION['ekyc_data']['mobileNumber'] = $mobileNumber;
        $_SESSION['ekyc_data']['aadhar'] = $aadhar;
        $_SESSION['ekyc_data']['bioenc'] = $bioenc;
        
        $request = [
        'mobileNumber' => $mobileNumber,
        ];

        $result = ekyc_otp_verification_send_api_run($request);
        
        if ($result && isset($result['sampleCode']) && $result['sampleCode'] == 200) {
            $otp_sent = true;
            $otp_message = $result['message'];
            $_SESSION['ekyc_data']['otp_sent'] = true;
        } else {
            $otp_error = $result['error'] ?? 'Failed to send OTP';
        }
        $current_step = 'otp';
    } 
    elseif (isset($_POST['verify_otp'])) {
        
        $mobileNumber = $_POST['mobileNumber'];
        $aadhar = $_SESSION['ekyc_data']['aadhar'] ?? $_POST['aadhar'];
        $bioenc = $_SESSION['ekyc_data']['biometric_data'] ?? $_POST['bioenc'];
        $otp = $_POST['otp'];
        
        $request = [
        'mobileNumber' => $mobileNumber,
        'otp' => $otp,
        ];

        $result = ekyc_otp_verification_verify_api_run($request);
        
        if ($result && isset($result['sampleCode']) && $result['sampleCode'] == 200) {
            $tng_token = $result['tng_token'];
            
            
            error_log("Final Submission - Aadhaar: $aadhar, Mobile: $mobileNumber, Token: $tng_token");
            error_log("Bioenc length: " . strlen($bioenc));
            error_log("Bioenc first 100 chars: " . substr($bioenc, 0, 100));
            
            
            echo "<form id='finalSubmitForm' action='Aadhar_advance_info_v1.php' method='post' style='display:none;'>
                    <input type='hidden' name='aadhar' value='".htmlspecialchars($aadhar, ENT_QUOTES)."'/>
                    <input type='hidden' name='mobileNumber' value='".htmlspecialchars($mobileNumber, ENT_QUOTES)."'/> 
                    <input type='hidden' name='tng_token' value='".htmlspecialchars($tng_token, ENT_QUOTES)."'/> 
                    <input type='hidden' name='bioenc' value='".htmlspecialchars($bioenc, ENT_QUOTES)."'/>
                  </form>
                  <script>
                    document.getElementById('finalSubmitForm').submit();
                  </script>";
            exit();
        } else {
            $otp_verify_error = $result['error'] ?? 'Invalid OTP or verification failed';
            $current_step = 'otp';
        }
    }
    elseif (isset($_POST['reset_form'])) {
       
        unset($_SESSION['ekyc_data']);
        $current_step = 'aadhaar';
    }
}


if (isset($_SESSION['ekyc_data']) && !empty($_SESSION['ekyc_data']['aadhar'])) {
    $current_step = 'otp';
    $aadhar = $_SESSION['ekyc_data']['aadhar'];
    $bioenc = $_SESSION['ekyc_data']['biometric_data'] ?? ($_SESSION['ekyc_data']['bioenc'] ?? '');
    if (isset($_SESSION['ekyc_data']['mobileNumber'])) {
        $mobileNumber = $_SESSION['ekyc_data']['mobileNumber'];
    }
    if (isset($_SESSION['ekyc_data']['otp_sent'])) {
        $otp_sent = $_SESSION['ekyc_data']['otp_sent'];
    }
} else {
    $current_step = 'aadhaar';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aadhaar E-KYC Verification</title>
    <style>
        
        .aadhar-box {
            background: #ffffff;
            border-radius: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            padding: 40px 30px;
            transition: all 0.3s ease;
            margin-top: 20px;
        }
        .aadhar-box:hover {
            box-shadow: 0 6px 25px rgba(0,0,0,0.15);
        }
        .input-group-text {
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 50%;
            width: 45px;
            height: 45px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .form-control {
            height: 55px;
            font-size: 1.2rem;
            border-radius: 50px;
            border: 2px solid #007bff33;
            text-align: center;
            letter-spacing: 2px;
            transition: 0.3s;
        }
        .form-control:focus {
            border-color: #007bff;
            box-shadow: 0 0 10px rgba(0,123,255,0.3);
        }
        .btn-primary {
            border-radius: 50px;
            padding: 12px 30px;
            font-size: 1rem;
            font-weight: 500;
            background: #007bff;
            border: none;
        }
        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-2px);
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            width: 120px;
        }
        .step:not(:last-child):after {
            content: '';
            position: absolute;
            top: 25px;
            right: -60px;
            width: 120px;
            height: 2px;
            background: #dee2e6;
        }
        .step.active:not(:last-child):after {
            background: #007bff;
        }
        .step-number {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #dee2e6;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 10px;
            z-index: 1;
            transition: all 0.3s ease;
        }
        .step.active .step-number {
            background: #007bff;
            color: white;
            transform: scale(1.1);
        }
        .step-label {
            font-size: 0.9rem;
            text-align: center;
            font-weight: 500;
        }
        .back-btn {
            background: #6c757d;
            border: none;
            border-radius: 50px;
            padding: 12px 25px;
            color: white;
            margin-right: 10px;
            transition: all 0.3s ease;
        }
        .back-btn:hover {
            background: #545b62;
            transform: translateY(-2px);
        }
        .alert {
            border-radius: 15px;
            border: none;
        }
        .d-none {
            display: none !important;
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
<div class="page-wrapper">
    <div class="page-content">
 <div class="d-flex justify-content-center align-items-center" style="min-height: 80vh;">
    <div class="col-lg-6 col-md-8">
        <div class="step-indicator">
            <div class="step <?php echo $current_step == 'aadhaar' ? 'active' : ''; ?>" id="step1">
                <div class="step-number">1</div>
                <div class="step-label">Aadhaar & Fingerprint</div>
            </div>
            <div class="step <?php echo $current_step == 'otp' ? 'active' : ''; ?>" id="step2">
                <div class="step-number">2</div>
                <div class="step-label">Mobile & OTP</div>
            </div>
            <div class="step" id="step3">
                <div class="step-number">3</div>
                <div class="step-label">Complete</div>
            </div>
        </div>
        
        <div class="aadhar-box fade-in">
            <div class="alert alert-primary bg-primary text-light border-0 alert-dismissible fade show" role="alert">
              <b>Advance Aadhar</b> — Successfully Working On All Devices ✅  
              <br>Automatic Detect (Rs. <?php echo $fee ?>)
            </div>

            
            <div id="aadhaar-section" style="<?php echo $current_step == 'aadhaar' ? 'display:block;' : 'display:none;'; ?>">
                <form id="captureForm">
                    <div class="mb-4">
                        <label for="txtUID" class="form-label fw-bold">Enter Aadhaar Number</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-id-card"></i></span>
                            <input class="form-control" id="txtUID" maxlength="12" name="EnterAadhaarNumber"
                                   type="text" autocomplete="off" placeholder="Enter 12 Digit Aadhaar Number" 
                                   value="<?php echo isset($aadhar) ? $aadhar : ''; ?>" />
                        </div>
                        <small class="text-muted d-block text-center mt-2">Example: 1234 5678 9012</small>
                    </div>

                    <div class="text-center mt-4">
                        <button type="button" class="btn btn-primary shadow-lg" name="capture" id="capture">
                            <i class="fas fa-fingerprint me-2"></i> Capture Finger
                        </button>
                    </div>
                </form>
            </div>

            
            <div id="otp-section" style="<?php echo $current_step == 'otp' ? 'display:block;' : 'display:none;'; ?>">
                <?php if (isset($otp_error)): ?>
                    <div class="alert alert-danger"><?php echo $otp_error; ?></div>
                <?php endif; ?>
                
                <?php if (isset($otp_verify_error)): ?>
                    <div class="alert alert-danger"><?php echo $otp_verify_error; ?></div>
                <?php endif; ?>
                
                <?php if (isset($otp_sent) && $otp_sent): ?>
                    <div class="alert alert-success"><?php echo $otp_message; ?></div>
                <?php endif; ?>
                
                <div class="mb-3 p-3 bg-light rounded">
                    <small class="text-muted"><i class="fas fa-info-circle me-2"></i>Aadhaar: <?php echo isset($aadhar) ? substr($aadhar, 0, 4) . 'XXXX' . substr($aadhar, 8) : ''; ?></small>
                </div>
                
                <form method="post" id="otpForm">
                    <input type="hidden" name="aadhar" value="<?php echo isset($aadhar) ? htmlspecialchars($aadhar) : ''; ?>">
                    <input type="hidden" name="bioenc" value="<?php echo isset($bioenc) ? htmlspecialchars($bioenc) : ''; ?>">
                    
                    <div class="mb-4">
                        <label for="mobileNumber" class="form-label fw-bold">Enter Mobile Number</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-mobile-alt"></i></span>
                            <input class="form-control" id="mobileNumber" maxlength="10" name="mobileNumber"
                                   type="text" autocomplete="off" placeholder="Enter 10 Digit Mobile Number" 
                                   value="<?php echo isset($mobileNumber) ? $mobileNumber : ''; ?>" />
                        </div>
                    </div>
                    
                    <div class="text-center mt-4 mb-3">
                        <button type="button" class="btn back-btn" id="backToAadhaar">
                            <i class="fas fa-arrow-left me-2"></i> Back
                        </button>
                        <button type="submit" name="send_otp" class="btn btn-primary shadow-lg" id="sendOtpBtn">
                            <i class="fas fa-paper-plane me-2"></i> Send OTP
                        </button>
                    </div>
                    
                    <div id="otpVerifySection" class="<?php echo (isset($otp_sent) && $otp_sent) ? '' : 'd-none'; ?>">
                        <div class="mb-4">
                            <label for="otp" class="form-label fw-bold">Enter OTP</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                                <input class="form-control" id="otp" maxlength="8" name="otp"
                                       type="text" autocomplete="off" placeholder="Enter OTP Received on Mobile" />
                            </div>
                        </div>
                        
                        <div class="text-center mt-4">
                            <button type="submit" name="verify_otp" class="btn btn-success shadow-lg">
                                <i class="fas fa-check me-2"></i> Verify & Submit
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
 </div>
</section>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    
    $("#capture").on('click', function(){
        var uid = $("#txtUID").val().trim();
        var alen = uid.length;

        if(uid === ''){
            alert('Please enter proper Aadhaar number');
            return;
        }
        if(alen != 12 || !/^\d{12}$/.test(uid)){
            alert('Please enter valid 12-digit Aadhaar number');
            return;
        }

        var ssoauth_ver = $.now();
        var data = { p: 'http', type:'AUTH', device: 'bio', isHttpsService: 'false' };

        
        var originalText = $("#capture").html();
        $("#capture").html('<i class="fas fa-spinner fa-spin me-2"></i> Capturing...');
        $("#capture").prop('disabled', true);

        $.getScript("<?php echo 'https://' . JkL_get('TheNextGenAPI','tng_apiurl'); ?>/printcapturekyc.js?v=" + ssoauth_ver)
        .done(function (script, textStatus) {
            if (textStatus === "success") {
                startCaptureRD({ authType: data.type, fpDevice: data.device, env: "P", isHttpsService: data.isHttpsService }, function (resp) {
                    
                    $("#capture").html(originalText);
                    $("#capture").prop('disabled', false);
                    
                    if(!resp || !resp.data){
                        alert('Capture failed or returned no data');
                        return;
                    }
                    
                    alert("Finger Captured Successfully ✅");
                    
                    
                    console.log("Biometric data captured, length:", resp.data.length);
                    console.log("First 200 chars:", resp.data.substring(0, 200));
                    
                    
                    var form = document.createElement('form');
                    form.method = 'POST';
                    form.action = '';
                    
                    var aadharInput = document.createElement('input');
                    aadharInput.type = 'hidden';
                    aadharInput.name = 'aadhar';
                    aadharInput.value = uid;
                    
                    var bioencInput = document.createElement('input');
                    bioencInput.type = 'hidden';
                    bioencInput.name = 'bioenc';
                    bioencInput.value = resp.data;
                    
                    var moveInput = document.createElement('input');
                    moveInput.type = 'hidden';
                    moveInput.name = 'move_to_otp';
                    moveInput.value = '1';
                    
                    form.appendChild(aadharInput);
                    form.appendChild(bioencInput);
                    form.appendChild(moveInput);
                    
                    document.body.appendChild(form);
                    form.submit();
                });
            } else {
                alert('Failed to load capture script.');
                $("#capture").html(originalText);
                $("#capture").prop('disabled', false);
            }
        })
        .fail(function(){
            alert('Could not load capture SDK. Check your internet or RD Service connection.');
            $("#capture").html(originalText);
            $("#capture").prop('disabled', false);
        });
    });
    
    
    $("#backToAadhaar").on('click', function(){
        
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = '';
        
        var resetInput = document.createElement('input');
        resetInput.type = 'hidden';
        resetInput.name = 'reset_form';
        resetInput.value = '1';
        
        form.appendChild(resetInput);
        document.body.appendChild(form);
        form.submit();
    });
    
    
    $("#mobileNumber").on('input', function(){
        var mobile = $(this).val().replace(/\D/g, '');
        $(this).val(mobile);
    });
    
    
    $("#txtUID").on('input', function(){
        var aadhaar = $(this).val().replace(/\D/g, '');
        $(this).val(aadhaar);
    });
    
    
    $("#otp").on('input', function(){
        var otp = $(this).val().replace(/\D/g, '');
        $(this).val(otp);
    });
    
    
    console.log("Current step: <?php echo $current_step; ?>");
    console.log("Aadhaar: <?php echo isset($aadhar) ? substr($aadhar, 0, 4) . 'XXXX' . substr($aadhar, 8) : 'Not set'; ?>");
    console.log("Bioenc length: <?php echo isset($bioenc) ? strlen($bioenc) : '0'; ?>");
});
</script>


<script src="https://kit.fontawesome.com/a2e0ad77b9.js" crossorigin="anonymous"></script>

</body>
</html>
<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>

<script src="jquery.maskedinput.js" type="text/javascript"></script>
<script src="jqueryold.js" type="text/javascript"></script>
<?php 
		include('../template/tngweb/footer.php');
		?>