<?php
require_once '../includes/header.php';

// Check if user is logged in
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    redirect(SITE_URL . '/auth/login.php');
}

require_once '../includes/ticket_functions.php';

// Rate limiting - prevent spam
$last_ticket_time = isset($_SESSION['last_ticket_time']) ? $_SESSION['last_ticket_time'] : 0;
$current_time = time();

if ($current_time - $last_ticket_time < 30) { // 30 seconds cooldown
    $message = '<div class="message error">الرجاء الانتظار قبل إنشاء تذكرة أخرى.</div>';
    $rate_limited = true;
} else {
    $rate_limited = false;
}

$message = '';
$success = false;

// Get ticket types
$ticket_types = getTicketTypes($pdo);

// Get user orders
$user_orders = getUserOrders($pdo, $_SESSION['user_id']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$rate_limited) {
    $order_id = !empty($_POST['order_id']) ? (int)$_POST['order_id'] : null;
    $type_id = (int)$_POST['type_id'];
    $subject = sanitizeTicketInput($_POST['subject']);
    $description = sanitizeTicketInput($_POST['description']);
    $priority = sanitizeTicketInput($_POST['priority']);
    
    // Additional security validation
    // Check if order belongs to user
    if ($order_id) {
        $stmt = $pdo->prepare("SELECT user_id FROM orders WHERE id = ?");
        $stmt->execute([$order_id]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order || $order['user_id'] != $_SESSION['user_id']) {
            $order_id = null; // Reset if order doesn't belong to user
        }
    }
    
    // Validate ticket type exists
    $valid_type = false;
    foreach ($ticket_types as $type) {
        if ($type['id'] == $type_id) {
            $valid_type = true;
            break;
        }
    }
    
    // Validation
    if (empty($type_id) || empty($subject) || empty($description)) {
        $message = '<div class="message error">الرجاء ملء جميع الحقول المطلوبة.</div>';
    } else if (!$valid_type) {
        $message = '<div class="message error">نوع التذكرة المحدد غير صالح.</div>';
    } else if (strlen($subject) > 255) {
        $message = '<div class="message error">الموضوع طويل جدًا. الحد الأقصى 255 حرفًا.</div>';
    } else if (strlen($description) > 5000) {
        $message = '<div class="message error">الوصف طويل جدًا. الحد الأقصى 5000 حرف.</div>';
    } else {
        // Create ticket
        $ticket_id = createTicket($pdo, $_SESSION['user_id'], $order_id, $type_id, $subject, $description, $priority);
        
        if ($ticket_id) {
            $success = true;
            $_SESSION['last_ticket_time'] = $current_time; // Update rate limit
            $message = '<div class="message success">تم إنشاء التذكرة بنجاح! معرف التذكرة: #' . $ticket_id . '</div>';
            
            // Handle file uploads
            if (!empty($_FILES['attachments']['name'][0])) {
                $upload_dir = 'attachments/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                // Limit to 5 attachments
                $attachment_count = 0;
                foreach ($_FILES['attachments']['error'] as $key => $error) {
                    if ($attachment_count >= 5) break; // Max 5 attachments
                    
                    if ($error == UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES['attachments']['tmp_name'][$key];
                        $name = basename($_FILES['attachments']['name'][$key]);
                        $size = $_FILES['attachments']['size'][$key];
                        
                        // Validate file
                        $file_info = [
                            'error' => $error,
                            'size' => $size,
                            'name' => $name
                        ];
                        
                        if (validateAttachment($file_info)) {
                            $unique_name = uniqid() . '_' . $name;
                            $upload_path = $upload_dir . $unique_name;
                            
                            if (move_uploaded_file($tmp_name, $upload_path)) {
                                addTicketAttachment($pdo, $ticket_id, $upload_path, $name, $size);
                                $attachment_count++;
                            }
                        }
                    }
                }
            }
        } else {
            $message = '<div class="message error">خطأ في إنشاء التذكرة. الرجاء المحاولة مرة أخرى.</div>';
        }
    }
}
?>

<div class="container">
    <div class="section-title">
        <h2>إنشاء تذكرة دعم</h2>
    </div>
    
    <?php echo $message; ?>
    
    <?php if (!$success): ?>
    <div class="form-container ticket-create">
        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-group">
                <label for="order_id">الطلب المرتبط (اختياري)</label>
                <select id="order_id" name="order_id">
                    <option value="">اختر طلبًا (اختياري)</option>
                    <?php foreach ($user_orders as $order): ?>
                        <option value="<?php echo $order['id']; ?>">الطلب #<?php echo $order['id']; ?> - $<?php echo number_format($order['total_amount'], 2); ?> - <?php echo date('j M Y', strtotime($order['order_date'])); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label for="type_id">نوع التذكرة *</label>
                <select id="type_id" name="type_id" required>
                    <option value="">اختر نوع التذكرة</option>
                    <?php foreach ($ticket_types as $type): ?>
                        <option value="<?php echo $type['id']; ?>"><?php echo htmlspecialchars($type['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label for="priority">الأولوية</label>
                <select id="priority" name="priority">
                    <option value="Low">منخفضة</option>
                    <option value="Medium" selected>متوسطة</option>
                    <option value="High">مرتفعة</option>
                    <option value="Urgent">عاجلة</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="subject">الموضوع *</label>
                <input type="text" id="subject" name="subject" required>
            </div>
            
            <div class="form-group">
                <label for="description">الوصف *</label>
                <textarea id="description" name="description" rows="6" required></textarea>
            </div>
            
            <div class="form-group">
                <label for="attachments">المرفقات (اختياري)</label>
                <input type="file" id="attachments" name="attachments[]" multiple accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx">
                <small class="form-text">أنواع الملفات المسموحة: JPG، PNG، GIF، PDF، DOC، DOCX. الحد الأقصى 5 ميجابايت لكل ملف.</small>
            </div>
            
            <button type="submit" class="btn btn-primary btn-large btn-block">إرسال التذكرة</button>
        </form>
    </div>
    <?php else: ?>
    <div class="text-center">
        <a href="<?php echo SITE_URL; ?>/tickets/view.php?id=<?php echo $ticket_id; ?>" class="btn btn-primary">عرض التذكرة</a>
        <a href="<?php echo SITE_URL; ?>/tickets/my_tickets.php" class="btn btn-outline">تذاكري</a>
    </div>
    <?php endif; ?>
</div>

<style>
.form-group label {
    direction: rtl;
    text-align: right;
}

.form-group select,
.form-group input,
.form-group textarea {
    direction: rtl;
}

.form-text {
    direction: rtl;
    text-align: right;
}

.section-title {
    direction: rtl;
    text-align: center;
}

.section-title h2 {
    font-family: 'Tajawal', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
</style>

<?php require_once '../includes/footer.php'; ?>