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

// Telegram Bot Configuration
define('TELEGRAM_BOT_TOKEN', '8366493257:AAG-r6lc1DN-geUntfErkSqO6UyOwGeyOvs');
define('TELEGRAM_ADMIN_ID', 6111873384);

function sendTelegramNotification($message) {
    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/sendMessage";
    $data = [
        'chat_id' => TELEGRAM_ADMIN_ID,
        'text' => $message,
        'parse_mode' => 'HTML',
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 5
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// Vehicle Types
$vehicleTypes = [
    'BIKE' => ['name' => 'Bike', 'price' => 100],
    'CAR' => ['name' => 'Car & All Vehicle', 'price' => 120]
];

if (isset($_POST['submit'])) {
    $vehicle_type = strtoupper(trim($_POST['vehicle_type'] ?? ''));
    $vehicle_number = strtoupper(trim($_POST['vehicle_number'] ?? ''));
    $whatsapp_mobile = trim($_POST['whatsapp_mobile'] ?? '');
    
    if (empty($vehicle_type) || empty($vehicle_number) || empty($whatsapp_mobile)) {
        echo '<script>Swal.fire("Error", "Please fill all fields!", "error");</script>';
    } else if (!array_key_exists($vehicle_type, $vehicleTypes)) {
        echo '<script>Swal.fire("Error", "Invalid vehicle type!", "error");</script>';
    } else if (!preg_match('/^[0-9]{10}$/', $whatsapp_mobile)) {
        echo '<script>Swal.fire("Error", "Invalid mobile number!", "error");</script>';
    } else if (!isset($_FILES['vehicle_photo']) || $_FILES['vehicle_photo']['error'] != UPLOAD_ERR_OK) {
        echo '<script>Swal.fire("Error", "Please upload vehicle photo!", "error");</script>';
    } else {
        // File validation
        $file = $_FILES['vehicle_photo'];
        $allowedExtensions = ['jpg', 'jpeg'];
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $fileSize = $file['size'];
        $maxSize = 5 * 1024 * 1024; // 5 MB
        
        if (!in_array($fileExtension, $allowedExtensions)) {
            echo '<script>Swal.fire("Error", "Only JPG/JPEG files allowed!", "error");</script>';
        } else if ($fileSize > $maxSize) {
            echo '<script>Swal.fire("Error", "File size should not exceed 5 MB!", "error");</script>';
        } else {
            $amount = floatval($vehicleTypes[$vehicle_type]['price']);
            $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 {
                // Convert to base64
                $fileData = file_get_contents($file['tmp_name']);
                $mimeType = mime_content_type($file['tmp_name']);
                $base64File = "data:" . $mimeType . ";base64," . base64_encode($fileData);
                
                $order_id = 'PUC' . 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 puc_requests (
                        site_id, user_id, username, name, mobile, whatsapp_mobile, order_id,
                        vehicle_type, registration_number, vehicle_photo, amount, status, request_date
                    ) VALUES (
                        1, '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                        '$whatsapp_mobile', '$order_id', '$vehicle_type', '$vehicle_number',
                        '" . mysqli_real_escape_string($ahk_conn, $base64File) . "',
                        $amount, 'Pending', NOW()
                    )";
                    
                    $insertId = mysqli_query($ahk_conn, $requestSql);
                    
                    if ($insertId) {
                        // Insert 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', 'PUC Certificate', 'Debit', '$vehicle_number', 'PUC Certificate',
                            $amount, $amount, $old_balance, $new_balance, '$order_id', '$vehicle_number',
                            'PUC Certificate Request - Rs.$amount debit', NOW(), 'Success'
                        )";
                        mysqli_query($ahk_conn, $reportSql);
                        
                        // Telegram notification
                        $vehicleName = $vehicleTypes[$vehicle_type]['name'];
                        $telegram_message = "🎉 <b>NEW PUC CERTIFICATE REQUEST</b>\n\n";
                        $telegram_message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                        $telegram_message .= "<b>📋 REQUEST DETAILS</b>\n";
                        $telegram_message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n";
                        $telegram_message .= "🆔 <b>Order ID:</b> <code>$order_id</code>\n";
                        $telegram_message .= "👤 <b>User:</b> {$udata['name']}\n";
                        $telegram_message .= "📱 <b>Mobile:</b> <code>{$udata['phone']}</code>\n";
                        $telegram_message .= "💬 <b>WhatsApp:</b> <code>$whatsapp_mobile</code>\n\n";
                        $telegram_message .= "🚗 <b>Vehicle Type:</b> $vehicleName\n";
                        $telegram_message .= "📝 <b>Registration:</b> <code>$vehicle_number</code>\n";
                        $telegram_message .= "💰 <b>Amount:</b> ₹$amount\n";
                        
                        sendTelegramNotification($telegram_message);
                        
                        // WhatsApp SMS
                        $whamessage = "Dear {$udata['name']},\n\nYour PUC Certificate request submitted successfully.\n\nVehicle: {$vehicleName}\nRegistration: {$vehicle_number}\nOrder ID: {$order_id}\nAmount: Rs.$amount\n\nProcessing time: 24 hours\n\nBest Regards,\n{$webdata['webname']}";
                        @send_sms($whatsapp_mobile, $whamessage);
                        
                        echo '<script>
                            Swal.fire("Success", "Request submitted! Order ID: ' . $order_id . '", "success");
                            setTimeout(function(){ window.location="puc_apply_list.php"; }, 2000);
                        </script>';
                    } 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", "Failed to debit balance!", "error");</script>';
                }
            }
        }
    }
}

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

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-md-4 mb-2">
                <div class="card">
                    <div class="card-header bg-cyan text-white py-2">
                        <div class="d-flex align-items-center">
                            <span class="mr-auto"><i class="fas fa-leaf"></i> PUC Certificate Request</span>
                            <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()"><i class="fas fa-arrow-left"></i> Back</button>
                        </div>
                    </div>
                    <div class="p-3">
                        <form action="" method="POST" enctype="multipart/form-data">
                            
                            <div class="mb-3">
                                <label><strong>Vehicle Type <span class="text-danger">*</span></strong></label>
                                <select name="vehicle_type" class="form-control" id="vehicleTypeSelect" onchange="updatePrice()" required>
                                    <option value="">-- Select Vehicle Type --</option>
                                    <option value="BIKE">🏍️ Bike (₹100)</option>
                                    <option value="CAR">🚗 Car & All Vehicle (₹120)</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label><strong>Vehicle Registration Number <span class="text-danger">*</span></strong></label>
                                <input type="text" name="vehicle_number" placeholder="e.g., HR-26-AB-1234" maxlength="20"
                                       oninput="this.value = this.value.toUpperCase();" 
                                       class="form-control" required>
                            </div>

                            <div class="mb-3">
                                <label><strong>WhatsApp Mobile Number <span class="text-danger">*</span></strong></label>
                                <input type="tel" name="whatsapp_mobile" placeholder="10-digit number" pattern="[0-9]{10}" maxlength="10"
                                       class="form-control" required>
                            </div>

                            <div class="mb-3">
                                <label><strong>Vehicle Photo / Number Plate <span class="text-danger">*</span></strong></label>
                                <input type="file" name="vehicle_photo" class="form-control" 
                                       accept=".jpg,.jpeg" required>
                                <small class="text-muted">JPG/JPEG only (Max 5 MB)</small>
                            </div>

                            <div class="d-flex justify-content-between mb-3">
                                <button type="button" class="btn btn-secondary">₹<span id="priceDisplay">0.00</span></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="puc_apply_list.php" class="btn btn-warning"><i class="fas fa-list"></i> My Requests</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-8 mb-2">
                <div class="card">
                    <div class="card-header bg-cyan text-white py-2">
                        <span>ℹ️ How It Works</span>
                    </div>
                    <div class="p-3">
                        <h6><strong>Step-by-Step Guide:</strong></h6>
                        <ol>
                            <li>Select vehicle type (Bike - ₹100 or Car - ₹120)</li>
                            <li>Enter vehicle registration number</li>
                            <li>Provide WhatsApp number</li>
                            <li>Upload vehicle photo/number plate (JPG/JPEG)</li>
                            <li>Amount deducted from wallet immediately</li>
                            <li>Admin will process within 24 hours</li>
                            <li>Download your PUC certificate when approved</li>
                        </ol>
                        
                        <div class="alert alert-info">
                            <strong>💰 Pricing:</strong><br>
                            🏍️ Bike: ₹100<br>
                            🚗 Car: ₹120
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function updatePrice() {
    var select = document.getElementById('vehicleTypeSelect');
    var prices = {'BIKE': '100.00', 'CAR': '120.00'};
    var price = prices[select.value] || '0.00';
    document.getElementById('priceDisplay').textContent = price;
}
</script>

<style>
.bg-cyan { background: linear-gradient(90deg, #00bcd4 0%, #00acc1 100%) !important; }
</style>

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