<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

if (!in_array($udata['type'], ['Master Distributor', 'Distributor', 'Retailer', 'admin'])) {
    require_once("404.php");
    exit;
}

if (!isset($udata['pan_aadhaar_otp_service']) || $udata['pan_aadhaar_otp_service'] != 'YES') {
    echo '<script>
        Swal.fire("Access Denied", "PAN by Aadhaar OTP service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

$show_popup = false;
$popup_order_id = '';
$popup_aadhaar = '';

if (isset($_POST['submit'])) {
    $aadhaar_number = trim($_POST['aadhaar_number']);
    $applicant_name = trim($_POST['applicant_name']);
    
    if (empty($aadhaar_number) || empty($applicant_name)) {
        echo '<script>Swal.fire("Error", "All fields required!", "error");</script>';
    } else if (!preg_match('/^[0-9]{12}$/', $aadhaar_number)) {
        echo '<script>Swal.fire("Error", "Enter valid 12-digit Aadhaar!", "error");</script>';
    } else {
        $amount = floatval($udata['pan_aadhaar_otp_fee'] ?? 50);
        $old_balance = floatval($udata['balance'] ?? 0);
        $new_balance = $old_balance - $amount;
        
        if ($old_balance < $amount) {
            echo '<script>Swal.fire("Insufficient Balance", "Need: ₹' . $amount . '", "error");</script>';
        } else {
            $order_id = 'PAN' . time() . rand(1000, 9999);
            
            $updateSuccess = mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
            
            if ($updateSuccess) {
                $requestSql = "INSERT INTO pan_aadhaar_otp_requests (
                    user_id, username, name, mobile, order_id, aadhaar_number, applicant_name,
                    amount, status, request_date
                ) VALUES (
                    '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                    '$order_id', '$aadhaar_number', '$applicant_name', $amount, 'Pending', NOW()
                )";
                
                $insertSuccess = mysqli_query($ahk_conn, $requestSql);
                
                if ($insertSuccess) {
                    $reportSql = "INSERT INTO reports (
                        site_id, user_id, username, name, operator, parent_id, order_id, service, type,
                        account_number, app_type, amount, main_amount, old_balance, new_balance,
                        txn_id, ref_id, description, date_time, status
                    ) VALUES (
                        1, '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['type']}', 0,
                        '$order_id', 'PAN Aadhaar OTP', 'Debit', '$aadhaar_number', 'PAN Card',
                        $amount, $amount, $old_balance, $new_balance, '$order_id', '$aadhaar_number',
                        'PAN Card by Aadhaar OTP - Rs.$amount debit', NOW(), 'Success'
                    )";
                    mysqli_query($ahk_conn, $reportSql);
                    
                    $whamessage = "Dear {$udata['name']},\n\nPAN Card Request Submitted!\n\nOrder ID: {$order_id}\nAadhaar: XXXX-XXXX-" . substr($aadhaar_number, -4) . "\n\nProcessing: 30 min";
                    @send_sms($udata['phone'], $whamessage);
                    
                    $show_popup = true;
                    $popup_order_id = $order_id;
                    $popup_aadhaar = 'XXXX-XXXX-' . substr($aadhaar_number, -4);
                    
                } else {
                    mysqli_query($ahk_conn, "UPDATE users SET balance = $old_balance WHERE phone = '{$udata['phone']}'");
                    echo '<script>Swal.fire("Error", "Failed. Balance restored.", "error");</script>';
                }
            } else {
                echo '<script>Swal.fire("Error", "Balance update failed!", "error");</script>';
            }
        }
    }
}

include('../template/ahkweb/header.php');
?>

<?php if($show_popup): ?>
<div class="popup-overlay" id="successPopup" style="display:flex;">
    <div class="popup-box">
        <div class="success-icon">✅</div>
        <h3>PAN Card Request Submitted!</h3>
        
        <div style="background:#f5f5f5;padding:15px;border-radius:10px;margin:20px 0;">
            <p><strong>Order ID:</strong> <?=$popup_order_id?></p>
            <p><strong>Aadhaar:</strong> <?=$popup_aadhaar?></p>
        </div>
        
        <div style="background:linear-gradient(135deg,#d1f2eb,#a3e4d7);padding:20px;border-radius:10px;text-align:center;">
            <h4 style="color:#138d75;">⏱️ Processing: 30 minutes</h4>
        </div>
        
        <button onclick="window.location='pan_aadhaar_list.php'" style="width:100%;background:#27ae60;color:white;border:none;padding:12px;border-radius:8px;cursor:pointer;margin-top:10px;">
            OK, Got It!
        </button>
    </div>
</div>
<script>
setTimeout(function(){ window.location='pan_aadhaar_list.php'; }, 5000);
</script>
<?php endif; ?>

<style>
.popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}
.popup-box {
    background: white;
    border-radius: 15px;
    padding: 30px;
    max-width: 450px;
    width: 90%;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}
.success-icon {
    font-size: 60px;
    text-align: center;
    margin-bottom: 15px;
}
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-md-5 mb-3">
                <div class="card">
                    <div class="card-header bg-success text-white py-2">
                        <div class="d-flex align-items-center">
                            <span><i class="fas fa-credit-card"></i> PAN Card Original PDF</span>
                            <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success py-2 mb-3 text-center">
                            <strong>🎯 Original PAN PDF मिलेगी</strong>
                        </div>
                        
                        <form method="POST">
                            <div class="mb-3">
                                <label><strong>Aadhaar Number <span class="text-danger">*</span></strong></label>
                                <input type="text" name="aadhaar_number" class="form-control" placeholder="12-digit Aadhaar" 
                                       maxlength="12" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><strong>Name (As on Aadhaar) <span class="text-danger">*</span></strong></label>
                                <input type="text" name="applicant_name" class="form-control" placeholder="Full Name" required>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <button type="button" class="btn btn-secondary">₹<?php echo number_format($udata['pan_aadhaar_otp_fee'] ?? 50, 2); ?></button>
                                <button type="submit" name="submit" class="btn btn-success" onclick="return confirm('Submit करना चाहते हैं?');">
                                    <i class="fas fa-paper-plane"></i> Submit
                                </button>
                                <a href="pan_aadhaar_list.php" class="btn btn-warning"><i class="fas fa-list"></i> My Requests</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-7 mb-3">
                <div class="card">
                    <div class="card-header bg-success text-white py-2">
                        <span>📋 Service Information</span>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h5><i class="fas fa-info-circle"></i> Service Details</h5>
                            <ul>
                                <li><b>Service:</b> PAN Card Original PDF</li>
                                <li><b>Method:</b> Aadhaar OTP Verification</li>
                                <li><b>Amount:</b> ₹<?php echo number_format($udata['pan_aadhaar_otp_fee'] ?? 50, 2); ?></li>
                                <li><b>Processing:</b> 30 minutes</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning">
                            <h5><i class="fas fa-exclamation-triangle"></i> Important</h5>
                            <ul>
                                <li>Original PAN PDF मिलेगी</li>
                                <li>Aadhaar में Registered Mobile पर OTP जाएगा</li>
                                <li>Name Aadhaar के अनुसार भरें</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('../admin/footers.php'); ?>