<?php
// Start output buffering at the very beginning
ob_start();
// Adding company field first in the ticket creation form.
include 'includes/header.php';

// Fetch enabled custom fields for tickets zone (always, not just on POST)
$custom_fields = [];
try {
    $stmt_cf = $pdo->prepare("SELECT * FROM custom_fields WHERE zone = 'tickets' AND is_active = 1 ORDER BY sort_order ASC, id ASC");
    $stmt_cf->execute();
    $custom_fields = $stmt_cf->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $custom_fields = [];
}

// Fetch products for related_service select menu, organized by categories
$related_products = [];
$related_products_by_category = [];
try {
    $stmt_products = $pdo->prepare("
        SELECT p.id, p.name, p.category_id, c.name as category_name 
        FROM products p 
        LEFT JOIN product_categories c ON p.category_id = c.id 
        WHERE p.is_active = 1 AND (p.hide_from_store IS NULL OR p.hide_from_store = 0) 
        ORDER BY c.name ASC, p.name ASC
    ");
    $stmt_products->execute();
    $related_products = $stmt_products->fetchAll(PDO::FETCH_ASSOC);

    // Group products by category
    foreach ($related_products as $product) {
        $category_name = $product['category_name'] ?? 'Uncategorized';
        if (!isset($related_products_by_category[$category_name])) {
            $related_products_by_category[$category_name] = [];
        }
        $related_products_by_category[$category_name][] = $product;
    }

    // Sort categories, putting "Uncategorized" at the end
    uksort($related_products_by_category, function ($a, $b) {
        if ($a === 'Uncategorized')
            return 1;
        if ($b === 'Uncategorized')
            return -1;
        return strcasecmp($a, $b);
    });

} catch (PDOException $e) {
    $related_products = [];
    $related_products_by_category = [];
}

$page_title = $lang_frontend['PAGE_TITLE_TICKET_CREATE'] ?? 'Create Ticket';

// Always check login first when guest tickets are disabled
if (!ALLOW_GUEST_TICKETS && !isLoggedIn()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_LOGIN_REQUIRED_TO_CREATE_TICKETS'] ?? 'You must be logged in to create tickets', 'warning');
    redirectTo('login');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_SECURITY_TOKEN'] ?? 'Invalid security token. Please try again.', 'danger');
        redirectTo('ticket_create');
        exit;
    }

    // Validate honeypot
    if (!validateHoneypot()) {
        // Bot detected, redirect with generic message
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_TICKET_SUBMITTED_SUCCESSFULLY_BOT'] ?? 'Ticket submitted successfully!', 'success');
        redirectTo('tickets');
        exit;
    }

    // Validate hCaptcha
    if (!validateHCaptcha($_POST['h-captcha-response'] ?? '')) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_HCAPTCHA_VERIFICATION_FAILED'] ?? 'Please complete the captcha verification to continue.', 'danger');
        redirectTo('ticket_create');
        exit;
    }

    // Get email for rate limiting (from session or form)
    $rate_limit_email = null;
    if (isLoggedIn()) {
        $rate_limit_email = $_SESSION['email'];
    } else {
        $rate_limit_email = sanitizeInput($_POST['email'] ?? '');
    }

    // Check rate limiting (uses config defaults)
    $rate_limit_check = checkRateLimit('ticket_create', $rate_limit_email);
    if (!$rate_limit_check['allowed']) {
        $_SESSION['alert'] = displayAlert($rate_limit_check['message'], 'warning');
        redirectTo('ticket_create');
        exit;
    }

    // Record this attempt for rate limiting
    recordSubmissionAttempt('ticket_create', $rate_limit_email);

    $subject = sanitizeInput($_POST['subject']);
    $description = cleanHTML($_POST['message']);
    $priority_raw = $_POST['priority'] ?? 'medium';
    $allowed_priorities = ['low', 'medium', 'high'];
    $priority = in_array(strtolower((string) $priority_raw), $allowed_priorities) ? strtolower((string) $priority_raw) : 'medium';
    $category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
    if ($category_id === false || $category_id === 0) { // Allow 0 or non-numeric to mean "no category"
        $category_id = null;
    }

    // Get user info from session if logged in, otherwise from form
    if (isLoggedIn()) {
        $email = $_SESSION['email'];
        $name = $_SESSION['name'];

        // Get company from database for logged-in user
        $stmt = $pdo->prepare("SELECT company FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user = $stmt->fetch();
        $company = $user['company'] ?? '';
    } else {
        $email_raw = $_POST['email'] ?? '';
        $email_validation = validateEmail($email_raw);
        if (!$email_validation['valid']) {
            $_SESSION['alert'] = displayAlert($email_validation['errors'][0] ?? $lang_alerts['ALERT_ERROR_INVALID_EMAIL_ADDRESS'] ?? 'Please enter a valid email address', 'danger');
            redirectTo('ticket_create');
        }
        $email = $email_validation['sanitized'];
        $name = sanitizeInput($_POST['name'] ?? '');
        $company = sanitizeInput($_POST['company'] ?? '');
		// Disallow ticket creation for blocked companies (guest mode only)
		foreach (BLOCKED_COMPANIES as $blocked) {
    		if (strcasecmp($company, $blocked) === 0) {
        	$_SESSION['alert'] = displayAlert('Registration from scammers is not allowed.', 'danger');
        	redirectTo('ticket_create');
        	exit;
    		}
		}
    }

    // Get related_service from form (optional) - validate as integer since it's a product ID
    $related_service = null;
    if (isset($_POST['related_service']) && !empty(trim($_POST['related_service']))) {
        $related_service_raw = trim($_POST['related_service']);
        $related_service_validated = filter_var($related_service_raw, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        if ($related_service_validated !== false) {
            $related_service = $related_service_validated;
        } else {
            // Invalid product ID - log and ignore
            error_log("Invalid related_service product ID in ticket creation: " . htmlspecialchars($related_service_raw, ENT_QUOTES, 'UTF-8'));
            $related_service = null;
        }
    }

    // Validate custom fields with length limits
    $custom_field_errors = [];
    $custom_field_values = [];
    foreach ($custom_fields as $cf) {
        $field_name = 'custom_field_' . $cf['id'];
        $value = '';
        if ($cf['type'] === 'checkboxes') {
            $value = isset($_POST[$field_name]) ? implode(',', (array) $_POST[$field_name]) : '';
        } elseif ($cf['type'] === 'checkbox') {
            $value = isset($_POST[$field_name]) ? '1' : '0';
        } else {
            $value = isset($_POST[$field_name]) ? trim($_POST[$field_name]) : '';
        }
        
        // Validate required fields (checkboxes: only required when the field is marked required)
        if ($cf['required'] && ($value === '' || ($cf['type'] === 'checkboxes' && empty($value)))) {
            $custom_field_errors[$cf['id']] = 'This field is required.';
        }
        
        // Enforce length limits based on field type
        if (!empty($value) && is_string($value)) {
            $max_length = 5000; // Default max length
            if ($cf['type'] === 'textarea') {
                $max_length = 10000;
            } elseif (in_array($cf['type'], ['text', 'email', 'url'])) {
                $max_length = 500;
            }
            
            if (strlen($value) > $max_length) {
                $custom_field_errors[$cf['id']] = "Field value exceeds maximum length of {$max_length} characters.";
            } else {
                // Truncate if necessary (but this shouldn't happen with proper validation)
                $value = substr($value, 0, $max_length);
            }
        }
        
        $custom_field_values[$cf['id']] = $value;
    }
    if (!empty($custom_field_errors)) {
        $_SESSION['alert'] = displayAlert('Please fill in all required custom fields.', 'danger');
        // Preserve entered values
        $_SESSION['custom_field_values'] = $custom_field_values;
    } else {
        // Upload attachment if provided
        $attachment = '';
        if (!empty($_FILES['attachment']['name'])) {
            $attachment = uploadFile($_FILES['attachment'], 'uploads/tickets/');

            if ($attachment === false) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_FILE_SIZE_TYPE'] ?? 'Invalid file. Please check file size and type.', 'danger');
                redirectTo('ticket_create');
                exit;
            }
        }

        // Insert ticket using prepared statement
        $user_id = isLoggedIn() ? $_SESSION['user_id'] : null;

        // Whitelist of allowed field names for security
        $allowed_fields = [
            'subject', 'message', 'attachment', 'priority', 'user_id', 'category_id',
            'email', 'name', 'company', 'related_service'
        ];

        // Define base fields from the tickets table (according to direct_setup)
        $fields = ['subject', 'message', 'attachment', 'priority', 'user_id', 'category_id'];
        $values = [$subject, $description, $attachment, $priority, $user_id, $category_id];
        $placeholders = ['?', '?', '?', '?', '?', '?'];

        // Add email field
        if (!empty($email)) {
            $field_name = 'email';
            if (in_array($field_name, $allowed_fields)) {
                $fields[] = $field_name;
                $values[] = $email;
                $placeholders[] = '?';
            }
        }

        // Add name field if user is not logged in
        if (!isLoggedIn() && !empty($name)) {
            $field_name = 'name';
            if (in_array($field_name, $allowed_fields)) {
                $fields[] = $field_name;
                $values[] = $name;
                $placeholders[] = '?';
            }
        }

        // Add company field
        if (!empty($company)) {
            $field_name = 'company';
            if (in_array($field_name, $allowed_fields)) {
                $fields[] = $field_name;
                $values[] = $company;
                $placeholders[] = '?';
            }
        }

        // Add related_service field (optional) - already validated as integer above
        if ($related_service !== null) {
            $field_name = 'related_service';
            if (in_array($field_name, $allowed_fields)) {
                $fields[] = $field_name;
                $values[] = $related_service; // Already validated as integer
                $placeholders[] = '?';
            }
        }

        // Validate all field names against whitelist before constructing query
        foreach ($fields as $field) {
            if (!in_array($field, $allowed_fields)) {
                error_log("Security: Attempted to use unauthorized field name in ticket creation: " . $field);
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_SECURITY_VIOLATION'] ?? 'Security violation detected. Please try again.', 'danger');
                redirectTo('ticket_create');
                exit;
            }
        }

        // Escape field names using backticks for additional safety
        $escaped_fields = array_map(function($field) use ($allowed_fields) {
            if (in_array($field, $allowed_fields)) {
                return '`' . $field . '`';
            }
            return null;
        }, $fields);
        $escaped_fields = array_filter($escaped_fields); // Remove any null values

        $query = "INSERT INTO tickets (" . implode(', ', $escaped_fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
        $stmt = $pdo->prepare($query);
        $stmt->execute($values);

        $ticket_id = $pdo->lastInsertId();

        // Save custom field values only after ticket is created
        foreach ($custom_fields as $cf) {
            $field_id = $cf['id'];
            $value = $custom_field_values[$field_id];
            $stmt_cfval = $pdo->prepare("INSERT INTO custom_field_values (field_id, value, item_id) VALUES (?, ?, ?)");
            $stmt_cfval->execute([$field_id, $value, $ticket_id]);
        }

        // Send notification to admins
        $email_ticket_subject = sprintf($lang_email['EMAIL_SUBJECT_NEW_TICKET_CREATED'] ?? "New Support Ticket Created: #%s - %s", $ticket_id, htmlspecialchars($subject));
        $ticket_link = getCleanUrl('ticket_view?id=' . $ticket_id);

        $creator_info_key = isLoggedIn() ? 'EMAIL_BODY_FIELD_CREATED_BY_USER' : 'EMAIL_BODY_FIELD_CREATED_BY_GUEST';
        $creator_info_params = isLoggedIn() ? [htmlspecialchars($name), $_SESSION['user_id']] : [htmlspecialchars($name), htmlspecialchars($email)];
        $creator_name_email_info = vsprintf($lang_email[$creator_info_key] ?? (isLoggedIn() ? 'Created By: %s (User ID: %s)' : 'Created By: %s (%s)'), $creator_info_params);


        $email_ticket_body = ($lang_email['EMAIL_BODY_NEW_TICKET_INTRO'] ?? "<p>A new support ticket has been created:</p>") .
            "<ul>" .
            "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_TICKET_ID'] ?? 'Ticket ID:') . "</strong> #" . $ticket_id . "</li>" .
            "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_TICKET_SUBJECT'] ?? 'Subject:') . "</strong> " . htmlspecialchars($subject) . "</li>" .
            "<li>" . $creator_name_email_info . "</li>" . // Already includes "Created By:"
            "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_COMPANY'] ?? 'Company:') . "</strong> " . htmlspecialchars($company) . "</li>" .
            "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_PRIORITY'] ?? 'Priority:') . "</strong> " . htmlspecialchars(ucfirst($priority)) . "</li>";

        if ($category_id) {
            $stmtCat = $pdo->prepare("SELECT name FROM ticket_categories WHERE id = ?");
            $stmtCat->execute([$category_id]);
            $categoryName = $stmtCat->fetchColumn();
            if ($categoryName) {
                $email_ticket_body .= "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_CATEGORY'] ?? 'Category:') . "</strong> " . htmlspecialchars($categoryName) . "</li>";
            }
        }
        $description = cleanHTML(html_entity_decode($description, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
        $email_ticket_body .= "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_DESCRIPTION'] ?? 'Description:') . "</strong><br>" . $description . "</li>" .
            "</ul>" .
            sprintf($lang_email['EMAIL_BODY_VIEW_TICKET_DETAILS_LINK'] ?? "<p>You can view the ticket details and respond here: <a href='%s'>%s</a></p>", $ticket_link, $ticket_link);

        notify_relevant_users('notify_ticket_creation', $email_ticket_subject, $email_ticket_body, [], true);

        $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_TICKET_SUBMITTED_SUCCESSFULLY_ID'] ?? 'Ticket submitted successfully! Your ticket ID is: %s', $ticket_id), 'success');


        // Redirect to tickets page - use the redirectTo helper function
        // The alert from above will be displayed on the tickets page.
        redirectTo('tickets');
    }
}

// Fetch ticket categories for the dropdown
$ticket_categories_list = [];
try {
    $stmtCategoriesFetch = $pdo->query("SELECT id, name, icon FROM ticket_categories ORDER BY name ASC");
    $ticket_categories_list = $stmtCategoriesFetch->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Log error, but don't break the page; category field will just be empty or not shown
    error_log("Error fetching categories for ticket_create.php: " . $e->getMessage());
}

// Support for ?category=CategoryName parameter
$preselect_category_id = '';
if (isset($_GET['category']) && $_GET['category'] !== '') {
    $category_param = strtolower(trim($_GET['category']));
    foreach ($ticket_categories_list as $cat) {
        if (strtolower($cat['name']) === $category_param) {
            $preselect_category_id = $cat['id'];
            break;
        }
    }
}

?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><?php echo $lang_frontend['TICKET_CREATE_CARD_HEADER'] ?? 'Submit a New Ticket'; ?>
                </h4>
            </div>
            <div class="card-body">
                <?php if (SITE_TICKET_MESSAGE !== ''): ?>
                    <p><?php echo SITE_TICKET_MESSAGE; ?></p>
                <?php endif; ?>
                <form action="<?php echo getCleanUrl('ticket_create'); ?>" method="post" enctype="multipart/form-data">
                    <?php if (isLoggedIn()): ?>
                        <!-- Company field removed for logged-in users - will use profile data -->
                        <?php
                        // Get user company from database to include in the submission
                        $stmt = $pdo->prepare("SELECT company FROM users WHERE id = ?");
                        $stmt->execute([$_SESSION['user_id']]);
                        $user = $stmt->fetch();
                        $company = $user['company'] ?? '';
                        ?>
                        <input type="hidden" name="company" value="<?php echo $company; ?>">
                        <!-- Hidden fields for logged-in users -->
                        <input type="hidden" name="name"
                            value="<?php echo htmlspecialchars($_SESSION['name'], ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="email"
                            value="<?php echo htmlspecialchars($_SESSION['email'], ENT_QUOTES, 'UTF-8'); ?>">
                    <?php elseif (ALLOW_GUEST_TICKETS): ?>
                        <div class="mb-3">
                            <label for="company"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_COMPANY'] ?? 'Company'; ?></label>
                            <input type="text" class="form-control" id="company" name="company">
                        </div>

                        <div class="mb-3">
                            <label for="name"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_YOUR_NAME'] ?? 'Your Name'; ?>
                                <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>

                        <div class="mb-3">
                            <label for="email"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_EMAIL_ADDRESS'] ?? 'Email Address'; ?>
                                <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                    <?php endif; ?>

                    <div class="mb-3">
                        <label for="subject"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_SUBJECT'] ?? 'Subject'; ?> <span
                                class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="subject" name="subject" required>
                    </div>


                    <?php if (!empty($ticket_categories_list)): ?>
                        <div class="mb-3" id="category_field_div">
                            <label
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_CATEGORY'] ?? 'Category'; ?></label>
                            <div class="row g-2" id="category-cards">
                                <div class="col-12 col-md-4">
                                    <div class="category-card card border-primary text-center flex-fill" data-category-id=""
                                        style="min-width: 120px; cursor: pointer; border-width:2px;">
                                        <div class="card-body py-2 px-1">
                                            <i class="bi bi-chat-text" style="font-size: 2rem;"></i>
                                            <div class="small mt-1">
                                                <?php echo $lang_frontend['FORM_SELECT_OPTION_NO_CATEGORY'] ?? 'No Category'; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php foreach ($ticket_categories_list as $cat): ?>
                                    <div class="col-12 col-md-4">
                                        <div class="category-card card text-center flex-fill"
                                            data-category-id="<?php echo htmlspecialchars($cat['id']); ?>"
                                            style="min-width: 120px; cursor: pointer;">
                                            <div class="card-body py-2 px-1">
                                                <?php if (!empty($cat['icon'])): ?>
                                                    <i class="bi bi-<?php echo htmlspecialchars($cat['icon']); ?>"
                                                        style="font-size: 2rem;"></i>
                                                <?php else: ?>
                                                    <i class="bi bi-chat-text" style="font-size: 2rem;"></i>
                                                <?php endif; ?>
                                                <div class="small mt-1"><?php echo htmlspecialchars($cat['name']); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <input type="hidden" name="category_id" id="category_id_hidden" value="">
                        </div>
                        <script>
                            document.addEventListener('DOMContentLoaded', function () {
                                const cards = document.querySelectorAll('.category-card');
                                const hiddenInput = document.getElementById('category_id_hidden');
                                // Preselect card based on PHP variable
                                let preselectId = <?php echo json_encode($preselect_category_id); ?>;
                                let selected = false;
                                cards.forEach(card => {
                                    if (card.getAttribute('data-category-id') == preselectId) { // use == not ===
                                        card.classList.add('border-primary', 'bg-primary', 'text-white');
                                        hiddenInput.value = preselectId;
                                        selected = true;
                                    } else {
                                        card.classList.remove('border-primary', 'bg-primary', 'text-white');
                                    }
                                });
                                // If no match, select the first card (No Category)
                                if (!selected && cards.length > 0) {
                                    cards[0].classList.add('border-primary', 'bg-primary', 'text-white');
                                    hiddenInput.value = '';
                                }
                                cards.forEach(card => {
                                    card.addEventListener('click', function () {
                                        cards.forEach(c => c.classList.remove('border-primary', 'bg-primary', 'text-white'));
                                        this.classList.add('border-primary', 'bg-primary', 'text-white');
                                        hiddenInput.value = this.getAttribute('data-category-id');
                                    });
                                });
                            });
                        </script>
                    <?php endif; ?>

                    <?php if (!empty($related_products_by_category)): ?>
                        <div class="mb-3">
                            <label for="related_service"
                                class="form-label"><?php echo $lang_frontend['TICKET_FORM_LABEL_RELATED_SERVICE'] ?? 'Related product or service'; ?></label>
                            <select class="form-select" id="related_service" name="related_service">
                                <option value="">
                                    <?php echo $lang_frontend['FORM_OPTION_SELECT_RELATED_SERVICE'] ?? '-- None --'; ?>
                                </option>
                                <?php
                                $selected_related_service = '';
                                if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                                    $selected_related_service = isset($_POST['related_service']) ? $_POST['related_service'] : '';
                                }

                                foreach ($related_products_by_category as $category_name => $products): ?>
                                    <optgroup label="<?php echo htmlspecialchars($category_name); ?>">
                                        <?php foreach ($products as $prod): ?>
                                            <option value="<?php echo htmlspecialchars($prod['id']); ?>" <?php echo ($selected_related_service == $prod['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($prod['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <?php foreach ($custom_fields as $cf):
                        $field_name = 'custom_field_' . $cf['id'];
                        $field_label = htmlspecialchars($cf['name']);
                        $is_required = $cf['required'] ? ' <span class="text-danger">*</span>' : '';
                        $possible_values = array_filter(array_map('trim', explode(',', $cf['possible_values'])));
                        $value = '';
                        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                            $value = isset($_POST[$field_name]) ? $_POST[$field_name] : '';
                        } elseif (isset($_SESSION['custom_field_values'][$cf['id']])) {
                            $value = $_SESSION['custom_field_values'][$cf['id']];
                        } elseif ($cf['type'] === 'radio' && !empty($possible_values)) {
                            $value = $possible_values[0]; // Preselect first radio option
                        }
                        ?>
                        <div class="mb-3">
                            <label class="form-label"><?php echo $field_label . $is_required; ?></label>
                            <?php if ($cf['type'] === 'text'): ?>
                                <input type="text" class="form-control" name="<?php echo $field_name; ?>"
                                    value="<?php echo htmlspecialchars($value); ?>" <?php echo $cf['required'] ? 'required' : ''; ?>>
                            <?php elseif ($cf['type'] === 'textarea'): ?>
                                <textarea class="form-control" name="<?php echo $field_name; ?>" rows="3" <?php echo $cf['required'] ? 'required' : ''; ?>><?php echo htmlspecialchars($value); ?></textarea>
                            <?php elseif ($cf['type'] === 'checkbox'): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="<?php echo $field_name; ?>" value="1"
                                        id="cf_<?php echo $cf['id']; ?>" <?php echo $value == '1' ? 'checked' : ''; ?>>
                                    <label class="form-check-label"
                                        for="cf_<?php echo $cf['id']; ?>"><?php echo $field_label; ?></label>
                                </div>
                            <?php elseif ($cf['type'] === 'checkboxes'): ?>
                                <div class="d-flex flex-column gap-1">
                                    <?php foreach ($possible_values as $pv): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="<?php echo $field_name; ?>[]"
                                                value="<?php echo htmlspecialchars($pv); ?>"
                                                id="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>" <?php echo (is_array($value) && in_array($pv, $value)) || (is_string($value) && in_array($pv, explode(',', $value))) ? 'checked' : ''; ?>>
                                            <label class="form-check-label"
                                                for="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>"><?php echo htmlspecialchars($pv); ?></label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php elseif ($cf['type'] === 'select'): ?>
                                <select class="form-select" name="<?php echo $field_name; ?>" <?php echo $cf['required'] ? 'required' : ''; ?>>
                                    <option value="">-- Select --</option>
                                    <?php foreach ($possible_values as $pv): ?>
                                        <option value="<?php echo htmlspecialchars($pv); ?>" <?php echo $value == $pv ? 'selected' : ''; ?>><?php echo htmlspecialchars($pv); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            <?php elseif ($cf['type'] === 'radio'): ?>
                                <div class="d-flex flex-column gap-1">
                                    <?php foreach ($possible_values as $pv): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="<?php echo $field_name; ?>"
                                                value="<?php echo htmlspecialchars($pv); ?>"
                                                id="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>" <?php echo $value == $pv ? 'checked' : ''; ?>>
                                            <label class="form-check-label"
                                                for="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>"><?php echo htmlspecialchars($pv); ?></label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($custom_field_errors[$cf['id']])): ?>
                                <div class="text-danger small mt-1"><?php echo $custom_field_errors[$cf['id']]; ?></div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>

                    <div class="mb-3">
                        <label for="description"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_DESCRIPTION'] ?? 'Description'; ?>
                            <span class="text-danger">*</span></label>

                        <textarea class="form-control" id="description" name="message" rows="5" required></textarea>
                    </div>

                    <div class="mb-3">
                        <label for="priority"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_PRIORITY'] ?? 'Priority'; ?></label>
                        <select class="form-select" id="priority" name="priority">
                            <option value="low"><?php echo $lang_frontend['TASK_PRIORITY_LOW'] ?? 'Low'; ?></option>
                            <option value="medium" selected>
                                <?php echo $lang_frontend['TASK_PRIORITY_MEDIUM'] ?? 'Medium'; ?></option>
                            <option value="high"><?php echo $lang_frontend['TASK_PRIORITY_HIGH'] ?? 'High'; ?></option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="attachment"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_ATTACHMENT_OPTIONAL'] ?? 'Attachment (Optional)'; ?></label>
                        <input type="file" class="form-control" id="attachment" name="attachment"
                            data-max-size="<?php echo MAX_UPLOAD_SIZE; ?>"
                            data-allowed-types="<?php echo implode(',', ALLOWED_EXTENSIONS); ?>">
                        <div class="form-text">
                            <?php echo sprintf($lang_frontend['FORM_TEXT_FILE_UPLOAD_CONSTRAINTS'] ?? 'Max file size: %s MB. Allowed file types: %s', MAX_UPLOAD_SIZE / 1024 / 1024, implode(', ', ALLOWED_EXTENSIONS)); ?>
                        </div>
                    </div>

                    <?php echo generateHCaptchaField(); ?>

                    <?php echo generateHoneypotField(); ?>

                    <!-- CSRF token -->
                    <input type="hidden" name="csrf_token" value="<?php echo generate_csrf_token(); ?>">

                    <div class="d-grid">
                        <button type="submit"
                            class="btn btn-primary btn-lg"><?php echo $lang_frontend['TICKET_CREATE_BUTTON_SUBMIT'] ?? 'Submit Ticket'; ?></button>
                    </div>
                </form>

                <script>
                    window.magicAIConfig = {
                        AI_OPENAI: '<?php echo AI_OPENAI; ?>',
                        AI_CLAUDE: '<?php echo AI_CLAUDE; ?>',
                        AI_GEMINI: '<?php echo AI_GEMINI; ?>',
                        AI_MISTRAL: '<?php echo AI_MISTRAL; ?>',
                        AI_DEEPSEEK: '<?php echo AI_DEEPSEEK; ?>'
                    };
                </script>
                <script>
                    $(document).ready(function () {
                        $('#description').summernote({
                            toolbar: [
                                ['style', ['bold', 'italic', 'underline', 'clear']],
                                ['para', ['ul', 'ol']],
                                ['insert', ['link']],
                                ['magic', ['SummernoteMagic']]
                            ],
                            height: 300,
                            minHeight: 150,
                            maxHeight: null,
                            dialogsFade: true,
                            dialogsInBody: true,
                            tabDisable: false,
                            spellCheck: true
                        });
                    });
                </script>


            </div>
        </div>
    </div>
</div>

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