<?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['dl_to_mobile_service']) || $udata['dl_to_mobile_service'] != 'YES') {
    echo '<script>
        Swal.fire("Access Denied", "DL to Mobile service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

// Telegram Configuration
define('TELEGRAM_DL_BOT_TOKEN', '8366493257:AAG-r6lc1DN-geUntfErkSqO6UyOwGeyOvs');
define('TELEGRAM_DL_ADMIN_ID', 6111873384);

$show_popup = false;
$popup_order_id = '';
$popup_dl_number = '';

if (isset($_POST['submit'])) {
    $dl_number = strtoupper(trim($_POST['dl_number']));
    $dob = trim($_POST['dob']);
    $new_mobile_number = trim($_POST['new_mobile_number']);
    $whatsapp_mobile = trim($_POST['whatsapp_mobile']);
    
    if (empty($dl_number) || empty($dob) || empty($new_mobile_number) || empty($whatsapp_mobile)) {
        echo '<script>Swal.fire("Error", "All fields required!", "error");</script>';
    } else if (!preg_match('/^[0-9]{10}$/', $new_mobile_number)) {
        echo '<script>Swal.fire("Error", "Enter valid 10-digit mobile!", "error");</script>';
    } else if (!preg_match('/^[0-9]{10}$/', $whatsapp_mobile)) {
        echo '<script>Swal.fire("Error", "Enter valid WhatsApp number!", "error");</script>';
    } else {
        $amount = floatval($udata['dl_to_mobile_fee'] ?? 150);
        $old_balance = floatval($udata['balance'] ?? 0);
        $new_balance = $old_balance - $amount;
        
        if ($old_balance < $amount) {
            echo '<script>Swal.fire("Insufficient Balance", "Need: ₹' . $amount . ', Have: ₹' . number_format($old_balance, 2) . '", "error");</script>';
        } else {
            $order_id = 'DLM' . time() . rand(1000, 9999);
            
            // Debit balance
            $updateSuccess = mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
            
            if ($updateSuccess) {
                // Insert request
                $requestSql = "INSERT INTO dl_to_mobile_requests (
                    site_id, user_id, username, name, mobile, whatsapp_mobile, order_id,
                    dl_number, dob, new_mobile_number, amount, status, request_date
                ) VALUES (
                    1, '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                    '$whatsapp_mobile', '$order_id', '$dl_number', '$dob', '$new_mobile_number',
                    $amount, 'Pending', NOW()
                )";
                
                $insertSuccess = mysqli_query($ahk_conn, $requestSql);
                
                if ($insertSuccess) {
                    // 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', 'DL Mobile Link', 'Debit', '$dl_number', 'DL Mobile Link',
                        $amount, $amount, $old_balance, $new_balance, '$order_id', '$dl_number',
                        'DL to Mobile Link - Rs.$amount debit', NOW(), 'Success'
                    )";
                    mysqli_query($ahk_conn, $reportSql);
                    
                    // Telegram notification
                    $telegram_message = "🆕 <b>NEW DL MOBILE LINK REQUEST</b>\n\n";
                    $telegram_message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                    $telegram_message .= "🆔 <b>Order ID:</b> <code>$order_id</code>\n";
                    $telegram_message .= "👤 <b>User:</b> {$udata['name']}\n";
                    $telegram_message .= "📱 <b>User Mobile:</b> <code>{$udata['phone']}</code>\n";
                    $telegram_message .= "💬 <b>WhatsApp:</b> <code>$whatsapp_mobile</code>\n\n";
                    $telegram_message .= "🚗 <b>DL Number:</b> <code>$dl_number</code>\n";
                    $telegram_message .= "📅 <b>DOB:</b> $dob\n";
                    $telegram_message .= "📞 <b>New Mobile:</b> <code>$new_mobile_number</code>\n";
                    $telegram_message .= "💰 <b>Amount:</b> ₹$amount\n";
                    
                    $url = "https://api.telegram.org/bot" . TELEGRAM_DL_BOT_TOKEN . "/sendMessage";
                    $ch = curl_init($url);
                    curl_setopt_array($ch, [
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => [
                            'chat_id' => TELEGRAM_DL_ADMIN_ID,
                            'text' => $telegram_message,
                            'parse_mode' => 'HTML'
                        ],
                        CURLOPT_SSL_VERIFYPEER => false,
                        CURLOPT_TIMEOUT => 10
                    ]);
                    curl_exec($ch);
                    curl_close($ch);
                    
                    // WhatsApp
                    $whamessage = "Dear {$udata['name']},\n\nDL Mobile Link Request Submitted!\n\nOrder ID: {$order_id}\nDL: {$dl_number}\nNew Mobile: {$new_mobile_number}\n\nProcessing: 30 min - 2 hours";
                    @send_sms($whatsapp_mobile, $whamessage);
                    
                    $show_popup = true;
                    $popup_order_id = $order_id;
                    $popup_dl_number = $dl_number;
                    
                } else {
                    mysqli_query($ahk_conn, "UPDATE users SET balance = $old_balance WHERE phone = '{$udata['phone']}'");
                    echo '<script>Swal.fire("Error", "Failed to save. 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>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>DL Number:</strong> <?=$popup_dl_number?></p>
        </div>
        
        <div style="background:linear-gradient(135deg,#fff3cd,#ffeaa7);padding:20px;border-radius:10px;text-align:center;">
            <h4 style="color:#d35400;">⏱️ Processing Time</h4>
            <p style="color:#e67e22;"><b>30 minutes to 2 hours</b></p>
        </div>
        
        <button onclick="window.location='dl_mobile_list.php'" style="width:100%;background:#3498db;color:white;border:none;padding:12px;border-radius:8px;font-size:16px;cursor:pointer;margin-top:10px;">
            OK, Got It!
        </button>
    </div>
</div>
<script>
setTimeout(function(){ window.location='dl_mobile_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-primary text-white py-2">
                        <div class="d-flex align-items-center">
                            <span><i class="fas fa-id-card"></i> DL to Mobile Link</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">
                        <form method="POST">
                            <div class="mb-3">
                                <label><strong>Driving License Number <span class="text-danger">*</span></strong></label>
                                <input type="text" name="dl_number" class="form-control" placeholder="DL12345678901234" 
                                       maxlength="20" oninput="this.value=this.value.toUpperCase().replace(/\s/g,'')" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><strong>Date of Birth <span class="text-danger">*</span></strong></label>
                                <input type="text" name="dob" class="form-control flatpickr-date" placeholder="DD/MM/YYYY" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><strong>New Mobile Number (Link करना है) <span class="text-danger">*</span></strong></label>
                                <input type="text" name="new_mobile_number" class="form-control" placeholder="10-digit number" 
                                       maxlength="10" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required>
                                <small class="text-muted">यह Number DL से Link होगा</small>
                            </div>
                            
                            <div class="mb-3">
                                <label><strong>WhatsApp Mobile <span class="text-danger">*</span></strong></label>
                                <input type="text" name="whatsapp_mobile" class="form-control" placeholder="10-digit number" 
                                       maxlength="10" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required>
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <button type="button" class="btn btn-secondary">₹<?php echo number_format($udata['dl_to_mobile_fee'] ?? 150, 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="dl_mobile_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-primary 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> DL to Mobile Link</li>
                                <li><b>Amount:</b> ₹<?php echo number_format($udata['dl_to_mobile_fee'] ?? 150, 2); ?></li>
                                <li><b>Processing Time:</b> 30 minutes - 2 hours</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning">
                            <h5><i class="fas fa-exclamation-triangle"></i> Important Notes</h5>
                            <ul>
                                <li>DL Number और DOB सही होना चाहिए</li>
                                <li>New Mobile Number DL से Link होगा</li>
                                <li>Processing में 30 min - 2 hours लग सकते हैं</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<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'); ?>