<?php
error_reporting(0);
set_time_limit(0);
date_default_timezone_set("Asia/Calcutta");
ini_set('max_execution_time', 600);
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
    ob_start("ob_gzhandler");
} else {
    ob_start();
}

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

if ($udata['ll_service'] != "YES") {
    echo '<script>
        Swal.fire("Access Denied", "You do not have LL Service active!", "error");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

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

// Telegram Configuration
if (!defined('TELEGRAM_LL_ADMIN_ID')) {
    define('TELEGRAM_LL_ADMIN_ID', '8100765831');
}
if (!defined('TELEGRAM_LL_BOT_TOKEN')) {
    define('TELEGRAM_LL_BOT_TOKEN', '8359738357:AAEGKHLBpR6c9vzD3xfmIn6dRwZnyRuzfeQ');
}

$show_popup = false;
$popup_order_id = '';
$popup_app_number = '';

if (isset($_POST['submit'])) {
    try {
        $applicationNumber = trim($_POST['applicationNumber']);
        $dob = trim($_POST['dob']);
        $password = trim($_POST['password']);
        $examsecretpin = trim($_POST['examsecretpin'] ?? '');
        $state = trim($_POST['state']);
        
        if (empty($applicationNumber) || empty($dob) || empty($password) || empty($state)) {
            echo '<script>
                Swal.fire("Error", "Please fill all required fields!", "error");
            </script>';
        } else {
            $amount = floatval($udata['ll_apply_fee'] ?? 100);
            $old_balance = floatval($udata['balance']);
            $new_balance = $old_balance - $amount;
            
            if ($old_balance < $amount) {
                echo '<script>
                    Swal.fire("Insufficient Balance", "Required: ₹' . $amount . ', Available: ₹' . number_format($old_balance, 2) . '", "error");
                </script>';
            } else {
                $order_id = 'LL' . time() . rand(1000, 9999);
                
                // Deduct balance
                $updateSuccess = mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
                
                if ($updateSuccess) {
                    // Insert transaction report
                    $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', 'LL Request', 'Debit', '$applicationNumber', 'LL Request',
                        $amount, $amount, $old_balance, $new_balance, '$order_id', '$applicationNumber',
                        'Rs.$amount debited for LL Request - $applicationNumber', NOW(), 'Success'
                    )";
                    mysqli_query($ahk_conn, $reportSql);
                    
                    // Insert LL request
                    $requestSql = "INSERT INTO ll_requests (
                        user_id, username, name, mobile, order_id, application_number, dob, password,
                        exam_secret_pin, state, amount, status, request_date
                    ) VALUES (
                        '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                        '$order_id', '$applicationNumber', '$dob', '$password', '$examsecretpin',
                        '$state', $amount, 'Pending', NOW()
                    )";
                    
                    $insertSuccess = mysqli_query($ahk_conn, $requestSql);
                    
                    if ($insertSuccess) {
                        // Telegram notification to admin
                        $telegram_msg = "🆕 <b>NEW LL REQUEST</b>\n\n";
                        $telegram_msg .= "👤 <b>User:</b> {$udata['name']}\n";
                        $telegram_msg .= "📱 <b>Mobile:</b> {$udata['phone']}\n";
                        $telegram_msg .= "━━━━━━━━━━━━━━━━\n";
                        $telegram_msg .= "📄 <b>App No:</b> $applicationNumber\n";
                        $telegram_msg .= "📍 <b>State:</b> $state\n";
                        $telegram_msg .= "🔑 <b>Password:</b> $password\n";
                        $telegram_msg .= "📅 <b>DOB:</b> $dob\n";
                        $telegram_msg .= "💰 <b>Amount:</b> ₹$amount";
                        
                        $url = "https://api.telegram.org/bot" . TELEGRAM_LL_BOT_TOKEN . "/sendMessage";
                        $ch = curl_init($url);
                        curl_setopt_array($ch, [
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_POST => true,
                            CURLOPT_POSTFIELDS => [
                                'chat_id' => TELEGRAM_LL_ADMIN_ID,
                                'text' => $telegram_msg,
                                'parse_mode' => 'HTML'
                            ],
                            CURLOPT_SSL_VERIFYPEER => false,
                            CURLOPT_TIMEOUT => 10
                        ]);
                        curl_exec($ch);
                        curl_close($ch);
                        
                        // WhatsApp to admin
                        $whamessage = "Dear Admin,\nNew LL Request\n\nOrder ID: *$order_id*\nApp No: *$applicationNumber*\nDOB: $dob\nState: $state\nPassword: $password";
                        @send_sms_credentials($webdata['phone'], $whamessage);
                        
                        $show_popup = true;
                        $popup_order_id = $order_id;
                        $popup_app_number = $applicationNumber;
                        
                    } else {
                        // Rollback
                        mysqli_query($ahk_conn, "UPDATE users SET balance = $old_balance WHERE phone = '{$udata['phone']}'");
                        echo '<script>Swal.fire("Error", "Failed to save request. Balance restored.", "error");</script>';
                    }
                } else {
                    echo '<script>Swal.fire("Error", "Balance update failed!", "error");</script>';
                }
            }
        }
    } catch (Exception $e) {
        echo '<script>Swal.fire("Error", "' . $e->getMessage() . '", "error");</script>';
    }
}

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

<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>

<?php if($show_popup): ?>
<div class="popup-overlay" id="successPopup" style="display:flex;">
    <div class="popup-box">
        <div class="success-icon">✅</div>
        <h3 style="text-align:center;color:#4CAF50;">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>Application:</strong> <?=$popup_app_number?></p>
        </div>
        
        <div style="background:linear-gradient(135deg,#FFF9C4,#FFEB3B);padding:20px;border-radius:10px;text-align:center;margin:20px 0;">
            <h4 style="color:#F57C00;">⏱️ Processing Time</h4>
            <p>Wait for <strong>30 minutes</strong></p>
        </div>
        
        <button onclick="window.location='ll_request_list.php'" style="width:100%;background:#4CAF50;color:white;border:none;padding:12px;border-radius:8px;font-size:16px;cursor:pointer;">
            OK, Got It!
        </button>
    </div>
</div>
<script>
setTimeout(function(){ window.location='ll_request_list.php'; }, 5000);
</script>
<?php endif; ?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-lg-5 mb-3">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-graduation-cap"></i> Learning License Request</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label><b>Application Number <span class="text-danger">*</span></b></label>
                                <input type="text" name="applicationNumber" class="form-control" placeholder="App****6545" maxlength="42" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><b>Password <span class="text-danger">*</span></b></label>
                                <input type="text" name="password" class="form-control" placeholder="SMS में मिला Password" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><b>Date of Birth <span class="text-danger">*</span></b></label>
                                <input type="text" name="dob" class="form-control flatpickr-date" placeholder="DD/MM/YYYY" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><b>Exam Pin <sup style="color:red">Optional</sup></b></label>
                                <input type="number" name="examsecretpin" class="form-control" placeholder="Only for Non-Aadhaar Mode">
                            </div>
                            
                            <div class="mb-3">
                                <label><b>Select State <span class="text-danger">*</span></b></label>
                                <select name="state" class="form-control" required>
                                    <option value="">-- Select State --</option>
                                    <option>Andhra Pradesh</option>
                                    <option>Arunachal Pradesh</option>
                                    <option>Assam</option>
                                    <option>Bihar</option>
                                    <option>Chhattisgarh</option>
                                    <option>Goa</option>
                                    <option>Gujarat</option>
                                    <option>Haryana</option>
                                    <option>Himachal Pradesh</option>
                                    <option>Jharkhand</option>
                                    <option>Karnataka</option>
                                    <option>Kerala</option>
                                    <option>Madhya Pradesh</option>
                                    <option>Maharashtra</option>
                                    <option>Manipur</option>
                                    <option>Meghalaya</option>
                                    <option>Mizoram</option>
                                    <option>Nagaland</option>
                                    <option>Odisha</option>
                                    <option>Punjab</option>
                                    <option>Rajasthan</option>
                                    <option>Sikkim</option>
                                    <option>Tamil Nadu</option>
                                    <option>Telangana</option>
                                    <option>Tripura</option>
                                    <option>Uttar Pradesh</option>
                                    <option>Uttarakhand</option>
                                    <option>West Bengal</option>
                                    <option>Delhi</option>
                                    <option>Jammu and Kashmir</option>
                                    <option>Ladakh</option>
                                </select>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <button type="button" class="btn btn-secondary">₹<?php echo number_format($udata['ll_apply_fee'] ?? 100, 2); ?></button>
                                <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?')">
                                    <i class="fas fa-paper-plane"></i> Submit
                                </button>
                                <a href="ll_request_list.php" class="btn btn-warning"><i class="fas fa-list"></i> My Requests</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-7 mb-3">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <span>📋 Important 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> Learning License Request</li>
                                <li><b>Amount:</b> ₹<?php echo number_format($udata['ll_apply_fee'] ?? 100, 2); ?></li>
                                <li><b>Processing Time:</b> 30 minutes</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning">
                            <h5><i class="fas fa-exclamation-triangle"></i> Important Notes</h5>
                            <ul>
                                <li>Password वो है जो SMS में मिला है</li>
                                <li>Exam Pin केवल Non-Aadhaar Mode के लिए</li>
                                <li>30 मिनट में result आ जाएगा</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
flatpickr(".flatpickr-date", {
    dateFormat: "d/m/Y",
    allowInput: true,
    maxDate: "today"
});
</script>

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