<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

// Authenticate
api_authenticate();

// Support JSON POST bodies
if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') === 0) {
    $input = json_decode(file_get_contents('php://input'), true);
    if (is_array($input)) {
        $_POST = array_merge($_POST, $input);
    }
}

// Validate and sanitize input
$subject = isset($_POST['subject']) ? sanitizeInput($_POST['subject']) : '';
$message = isset($_POST['message']) ? (function_exists('cleanHTML') ? cleanHTML($_POST['message']) : sanitizeInput($_POST['message'])) : '';
$user_email_raw = $_POST['user_email'] ?? '';
$name = isset($_POST['name']) ? sanitizeInput($_POST['name']) : '';
$company = isset($_POST['company']) ? sanitizeInput($_POST['company']) : '';
$priority_raw = $_POST['priority'] ?? 'medium';
$category_id_raw = $_POST['category_id'] ?? null;
$custom_fields_json = $_POST['custom_fields'] ?? '{}';

// Validate email using centralized function
$email_validation = validateEmail($user_email_raw);
if (!$email_validation['valid']) {
    echo json_encode(['success' => false, 'error' => 'Invalid email address', 'email_errors' => $email_validation['errors']]);
    exit;
}
$user_email = $email_validation['sanitized'];

// Validate priority against allowed values
$allowed_priorities = ['low', 'medium', 'high'];
$priority = in_array(strtolower($priority_raw), $allowed_priorities) ? strtolower($priority_raw) : 'medium';

// Validate category_id as integer
$category_id = null;
if ($category_id_raw !== null && $category_id_raw !== '') {
    $category_id_validated = filter_var($category_id_raw, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    if ($category_id_validated !== false) {
        $category_id = $category_id_validated;
    }
}

// Validate and sanitize custom fields JSON
$custom_fields = json_decode($custom_fields_json, true);
if (!is_array($custom_fields)) {
    $custom_fields = [];
}

// Validate required fields
if (empty($subject) || empty($message) || empty($user_email)) {
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit;
}

// Validate subject and message length
if (strlen($subject) > 500) {
    echo json_encode(['success' => false, 'error' => 'Subject is too long (maximum 500 characters)']);
    exit;
}
if (strlen($message) > 10000) {
    echo json_encode(['success' => false, 'error' => 'Message is too long (maximum 10000 characters)']);
    exit;
}

// Fetch active custom fields for tickets
$stmt_cf = $pdo->prepare("SELECT * FROM custom_fields WHERE zone = 'tickets' AND is_active = 1");
$stmt_cf->execute();
$active_custom_fields = $stmt_cf->fetchAll(PDO::FETCH_ASSOC);

// Validate required custom fields and enforce length limits
$custom_field_errors = [];
foreach ($active_custom_fields as $cf) {
    $fid = (string) $cf['id'];
    $is_required = $cf['required'];
    $value = $custom_fields[$fid] ?? '';

    // Sanitize custom field value
    if (is_string($value)) {
        $value = sanitizeInput($value);
    }

    // Validate required fields
    if ($is_required && ($value === '' || $value === null)) {
        $custom_field_errors[$fid] = '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[$fid] = "Field value exceeds maximum length of {$max_length} characters.";
        }
    }

    // Update sanitized value back to array
    $custom_fields[$fid] = $value;
}
if (!empty($custom_field_errors)) {
    echo json_encode(['success' => false, 'error' => 'Missing required custom fields', 'custom_field_errors' => $custom_field_errors]);
    exit;
}

// Insert ticket
$fields = ['subject', 'message', 'priority', 'email'];
$values = [$subject, $message, $priority, $user_email];
$placeholders = ['?', '?', '?', '?'];
if (!empty($name)) {
    $fields[] = 'name';
    $values[] = $name;
    $placeholders[] = '?';
}
if (!empty($company)) {
    $fields[] = 'company';
    $values[] = $company;
    $placeholders[] = '?';
}
if (!empty($category_id)) {
    $fields[] = 'category_id';
    $values[] = $category_id;
    $placeholders[] = '?';
}
$stmt_u = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
$stmt_u->execute([$user_email]);
$account_user_id = $stmt_u->fetchColumn();
if ($account_user_id) {
    $fields[] = 'user_id';
    $values[] = (int) $account_user_id;
    $placeholders[] = '?';
}
$query = "INSERT INTO tickets (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt = $pdo->prepare($query);
$stmt->execute($values);
$ticket_id = $pdo->lastInsertId();

// Insert custom field values
foreach ($active_custom_fields as $cf) {
    $fid = (string) $cf['id'];
    $value = $custom_fields[$fid] ?? '';
    $stmt_cfval = $pdo->prepare("INSERT INTO custom_field_values (field_id, value, item_id) VALUES (?, ?, ?)");
    $stmt_cfval->execute([$fid, $value, $ticket_id]);
}

// Admin notification (copied from ticket_create.php)
$lang_email = include __DIR__ . '/../languages/English-US/lang.php';
$email_ticket_subject = sprintf($lang_email['EMAIL_SUBJECT_NEW_TICKET_CREATED-API'] ?? "New Support Ticket Created from API: #%s - %s", $ticket_id, htmlspecialchars($subject));
$ticket_link = (defined('BASE_URL') ? BASE_URL : '') . '/ticket_view?id=' . $ticket_id;
$creator_name_email_info = sprintf($lang_email['EMAIL_BODY_FIELD_CREATED_BY_GUEST'] ?? 'Created By: %s (%s)', htmlspecialchars($name), htmlspecialchars($user_email));
$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>" .
    "<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>";
    }
}
$email_ticket_body .= "<li><strong>" . ($lang_email['EMAIL_BODY_FIELD_DESCRIPTION'] ?? 'Description:') . "</strong><br>" . nl2br(htmlspecialchars($message)) . "</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);

echo json_encode(['success' => true, 'ticket_id' => $ticket_id]);