<?php
include __DIR__ . '/../includes/header.php';

// Enable error reporting only in debug mode
if (defined('DEBUG_MODE') && DEBUG_MODE) {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

if (!isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_ACCESS_REQUIRED'], 'danger');
    redirectTo(getCleanUrl('index'));
    exit;
}

$page_title = 'Custom Fields';

// Fetch all custom fields
$stmt = $pdo->query("SELECT * FROM custom_fields ORDER BY sort_order ASC, id ASC");
$fields = $stmt->fetchAll();

$zone_labels = [
    'tickets' => $lang['LBL_ZONE_TICKETS'] ?? 'Tickets',
    'profile' => $lang['LBL_ZONE_PROFILE'] ?? 'Profile',
];
$type_labels = [
    'text' => $lang['LBL_TYPE_TEXT'] ?? 'Text',
    'textarea' => $lang['LBL_TYPE_TEXTAREA'] ?? 'Textarea',
    'checkbox' => $lang['LBL_TYPE_CHECKBOX'] ?? 'Checkbox',
    'checkboxes' => $lang['LBL_TYPE_CHECKBOXES'] ?? 'Checkboxes',
    'select' => $lang['LBL_TYPE_SELECT'] ?? 'Select',
    'radio' => $lang['LBL_TYPE_RADIO'] ?? 'Radio',
];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'], 'danger');
        redirectTo('admin/custom_fields');
        exit;
    }
    // Add new field
    if (isset($_POST['add_field'])) {
        $name = sanitizeInput($_POST['name']);
        $zone = in_array($_POST['zone'], ['tickets','profile']) ? $_POST['zone'] : 'tickets';
        $type = in_array($_POST['type'], ['text','textarea','checkbox','checkboxes','select','radio']) ? $_POST['type'] : 'text';
        
        // Validate field name
        if (empty(trim($name)) || strlen($name) > 100) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_CUSTOM_FIELD_NAME_LENGTH'], 'danger');
            redirectTo('admin/custom_fields');
            exit;
        }
        
        // Check for duplicate field names in the same zone
        $stmt_check = $pdo->prepare("SELECT id FROM custom_fields WHERE name = ? AND zone = ?");
        $stmt_check->execute([$name, $zone]);
        if ($stmt_check->fetch()) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_EXISTS_IN_ZONE'], $zone), 'danger');
            redirectTo('admin/custom_fields');
            exit;
        }
        
        $possible_values = '';
        if (in_array($type, ['checkboxes','select','radio'])) {
            if (isset($_POST['possible_values'])) {
                if (is_array($_POST['possible_values'])) {
                    $possible_values = implode(',', array_map('trim', $_POST['possible_values']));
                } else {
                    $possible_values = trim($_POST['possible_values']);
                }
            }
            
            // Validate that possible values are provided for fields that require them
            if (empty($possible_values)) {
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_VALUES_REQUIRED'], $type), 'danger');
                redirectTo('admin/custom_fields');
                exit;
            }
        }
        
        $required = isset($_POST['required']) ? 1 : 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $sort_order = isset($_POST['sort_order']) ? max(0, (int)$_POST['sort_order']) : 0;
        try {
            $stmt = $pdo->prepare("INSERT INTO custom_fields (name, zone, type, possible_values, required, is_active, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $zone, $type, $possible_values, $required, $is_active, $sort_order]);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_CUSTOM_FIELD_ADDED_SUCCESS'], 'success');
        } catch (PDOException $e) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_ADD_ERROR'], $e->getMessage()), 'danger');
        }
        redirectTo('admin/custom_fields');
        exit;
    }
    // Edit field
    if (isset($_POST['edit_field'])) {
        $id = (int)$_POST['id'];
        $name = sanitizeInput($_POST['name']);
        $zone = in_array($_POST['zone'], ['tickets','profile']) ? $_POST['zone'] : 'tickets';
        $type = in_array($_POST['type'], ['text','textarea','checkbox','checkboxes','select','radio']) ? $_POST['type'] : 'text';
        
        // Validate field ID
        if ($id <= 0) {
            $_SESSION['alert'] = displayAlert('Invalid field ID.', 'danger');
            redirectTo('admin/custom_fields');
            exit;
        }
        
        // Validate field name
        if (empty(trim($name)) || strlen($name) > 100) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_CUSTOM_FIELD_NAME_LENGTH'], 'danger');
            redirectTo('admin/custom_fields');
            exit;
        }
        
        // Check for duplicate field names in the same zone (excluding current field)
        $stmt_check = $pdo->prepare("SELECT id FROM custom_fields WHERE name = ? AND zone = ? AND id != ?");
        $stmt_check->execute([$name, $zone, $id]);
        if ($stmt_check->fetch()) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_EXISTS_IN_ZONE'], $zone), 'danger');
            redirectTo('admin/custom_fields');
            exit;
        }
        
        $possible_values = '';
        if (in_array($type, ['checkboxes','select','radio'])) {
            // Always get possible_values from the hidden input (which is updated by JS)
            if (isset($_POST['possible_values'])) {
                $possible_values = trim($_POST['possible_values']);
            }
            
            // Validate that possible values are provided for fields that require them
            if (empty($possible_values)) {
                $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_VALUES_REQUIRED'], $type), 'danger');
                redirectTo('admin/custom_fields');
                exit;
            }
        }
        
        $required = isset($_POST['required']) ? 1 : 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $sort_order = isset($_POST['sort_order']) ? max(0, (int)$_POST['sort_order']) : 0;
        try {
            $stmt = $pdo->prepare("UPDATE custom_fields SET name=?, zone=?, type=?, possible_values=?, required=?, is_active=?, sort_order=? WHERE id=?");
            $stmt->execute([$name, $zone, $type, $possible_values, $required, $is_active, $sort_order, $id]);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_CUSTOM_FIELD_UPDATED_SUCCESS'], 'success');
        } catch (PDOException $e) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_UPDATE_ERROR'], $e->getMessage()), 'danger');
        }
        redirectTo('admin/custom_fields');
        exit;
    }
    // Delete field
    if (isset($_POST['delete_field'])) {
        $id = (int)$_POST['id'];
        
        // Validate field ID
        if ($id <= 0) {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_FIELD_ID'], 'danger');
            redirectTo('admin/custom_fields');
            exit;
        }
        
        try {
            // First delete related custom field values to prevent orphaned records
            $stmt_values = $pdo->prepare("DELETE FROM custom_field_values WHERE field_id = ?");
            $stmt_values->execute([$id]);
            
            // Then delete the custom field
            $stmt = $pdo->prepare("DELETE FROM custom_fields WHERE id = ?");
            $stmt->execute([$id]);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_CUSTOM_FIELD_DELETED_SUCCESS'], 'success');
        } catch (PDOException $e) {
            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_CUSTOM_FIELD_DELETE_ERROR'], $e->getMessage()), 'danger');
        }
        redirectTo('admin/custom_fields');
        exit;
    }
}
?>
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1><?php echo $lang['ADMIN_CUSTOM_FIELDS_PAGE_TITLE'] ?? 'Custom Fields'; ?></h1>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addFieldModal">
            <i class="bi bi-plus-circle"></i> <?php echo $lang['ADMIN_CUSTOM_FIELDS_BTN_ADD'] ?? 'Add Custom Field'; ?>
        </button>
        <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
            <i class="bi bi-arrow-left"></i> <?php echo $lang['ADMIN_INVOICES_BTN_BACK_TO_DASHBOARD'] ?? 'Back to Dashboard'; ?>
        </a>
    </div>
    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th><?php echo $lang['LBL_NAME'] ?? 'Name'; ?></th>
                    <th><?php echo $lang['LBL_ZONE'] ?? 'Zone'; ?></th>
                    <th><?php echo $lang['TABLE_HEADER_STATUS'] ?? 'Status'; ?></th>
                    <th><?php echo $lang['TABLE_HEADER_ORDER'] ?? 'Order'; ?></th>
                    <th><?php echo $lang['TABLE_HEADER_ACTIONS'] ?? 'Actions'; ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($fields as $field): ?>
                <tr>
                    <td><?php echo htmlspecialchars($field['name']); ?></td>
                    <td><?php echo $zone_labels[$field['zone']] ?? $field['zone']; ?></td>
                    <td>
                        <span class="badge <?php echo $field['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                            <?php echo $field['is_active'] ? ($lang['STATUS_ENABLED'] ?? 'Enabled') : ($lang['STATUS_DISABLED'] ?? 'Disabled'); ?>
                        </span>
                    </td>
                    <td><?php echo (int)$field['sort_order']; ?></td>
                    <td>
                        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editFieldModal<?php echo $field['id']; ?>">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteFieldModal<?php echo $field['id']; ?>">
                            <i class="bi bi-trash"></i>
                        </button>
                        <!-- Edit Modal (one per field) -->
                        <div class="modal fade" id="editFieldModal<?php echo $field['id']; ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form method="post">
                                        <?php echo get_csrf_input_field(); ?>
                                        <input type="hidden" name="id" value="<?php echo $field['id']; ?>">
                                        <div class="modal-header">
                                            <h5 class="modal-title"><?php echo $lang['ADMIN_CUSTOM_FIELDS_MODAL_TITLE_EDIT'] ?? 'Edit Custom Field'; ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="mb-3">
                                                <label class="form-label"><?php echo $lang['LBL_NAME'] ?? 'Name'; ?></label>
                                                <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($field['name']); ?>" required>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label"><?php echo $lang['LBL_ZONE'] ?? 'Zone'; ?></label>
                                                <select class="form-select" name="zone" required>
                                                    <option value="tickets" <?php if ($field['zone'] === 'tickets') echo 'selected'; ?>><?php echo $zone_labels['tickets']; ?></option>
                                                    <option value="profile" <?php if ($field['zone'] === 'profile') echo 'selected'; ?>><?php echo $zone_labels['profile']; ?></option>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label"><?php echo $lang['LBL_TYPE'] ?? 'Type'; ?></label>
                                                <select class="form-select field-type-select" name="type" data-modal="editFieldModal<?php echo $field['id']; ?>" required>
                                                    <?php foreach ($type_labels as $type => $label): ?>
                                                        <option value="<?php echo $type; ?>" <?php if ($field['type'] === $type) echo 'selected'; ?>><?php echo $label; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="mb-3 d-none possible-values-section" id="possibleValuesSection-editFieldModal<?php echo $field['id']; ?>">
                                                <label class="form-label"><?php echo $lang['LBL_POSSIBLE_VALUES_HELP'] ?? 'Possible Values (one per line, drag to reorder)'; ?></label>
                                                <ul class="list-group possible-values-list" data-input="possibleValuesInput-editFieldModal<?php echo $field['id']; ?>">
                                                    <?php
                                                    $values = array_filter(array_map('trim', explode(',', $field['possible_values'])));
                                                    foreach ($values as $v): ?>
                                                        <li class="list-group-item d-flex align-items-center">
                                                            <span class="flex-grow-1"><?php echo htmlspecialchars($v); ?></span>
                                                            <button type="button" class="btn btn-sm btn-outline-danger ms-2 remove-value-btn">&times;</button>
                                                        </li>
                                                    <?php endforeach; ?>
                                                </ul>
                                                <input type="hidden" name="possible_values" id="possibleValuesInput-editFieldModal<?php echo $field['id']; ?>" value="<?php echo htmlspecialchars($field['possible_values']); ?>">
                                                <div class="input-group mt-2">
                                                    <input type="text" class="form-control add-value-input" placeholder="<?php echo $lang['PLACEHOLDER_ADD_VALUE'] ?? 'Add value...'; ?>">
                                                    <button type="button" class="btn btn-outline-secondary add-value-btn"><?php echo $lang['BUTTON_ADD'] ?? 'Add'; ?></button>
                                                </div>
                                            </div>
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="checkbox" name="required" id="required-editFieldModal<?php echo $field['id']; ?>" value="1" <?php if ($field['required']) echo 'checked'; ?>>
                                                <label class="form-check-label" for="required-editFieldModal<?php echo $field['id']; ?>"><?php echo $lang['STATUS_REQUIRED'] ?? 'Required'; ?></label>
                                            </div>
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="checkbox" name="is_active" id="isActive-editFieldModal<?php echo $field['id']; ?>" value="1" <?php if ($field['is_active']) echo 'checked'; ?>>
                                                <label class="form-check-label" for="isActive-editFieldModal<?php echo $field['id']; ?>"><?php echo $lang['STATUS_ENABLED'] ?? 'Enabled'; ?></label>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label"><?php echo $lang['TABLE_HEADER_ORDER'] ?? 'Order'; ?></label>
                                                <input type="number" class="form-control" name="sort_order" value="<?php echo (int)$field['sort_order']; ?>" min="0">
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                                            <button type="submit" name="edit_field" class="btn btn-primary"><?php echo $lang['BUTTON_SAVE_CHANGES'] ?? 'Save Changes'; ?></button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <!-- Delete Modal -->
                        <div class="modal fade" id="deleteFieldModal<?php echo $field['id']; ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form method="post">
                                        <?php echo get_csrf_input_field(); ?>
                                        <input type="hidden" name="id" value="<?php echo $field['id']; ?>">
                                        <div class="modal-header">
                                            <h5 class="modal-title"><?php echo $lang['ADMIN_CUSTOM_FIELDS_MODAL_TITLE_DELETE'] ?? 'Delete Custom Field'; ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <p><?php echo sprintf($lang['ADMIN_CUSTOM_FIELDS_DELETE_CONFIRM'] ?? 'Are you sure you want to delete the custom field <strong>%s</strong>?', htmlspecialchars($field['name'])); ?></p>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                                            <button type="submit" name="delete_field" class="btn btn-danger"><?php echo $lang['BUTTON_DELETE'] ?? 'Delete'; ?></button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add Field Modal -->
<div class="modal fade" id="addFieldModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <?php echo get_csrf_input_field(); ?>
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo $lang['ADMIN_CUSTOM_FIELDS_MODAL_TITLE_ADD'] ?? 'Add Custom Field'; ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo $lang['LBL_NAME'] ?? 'Name'; ?></label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo $lang['LBL_ZONE'] ?? 'Zone'; ?></label>
                        <select class="form-select" name="zone" required>
                            <option value="tickets"><?php echo $zone_labels['tickets']; ?></option>
                            <option value="profile"><?php echo $zone_labels['profile']; ?></option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo $lang['LBL_TYPE'] ?? 'Type'; ?></label>
                        <select class="form-select field-type-select" name="type" data-modal="addFieldModal" required>
                            <?php foreach ($type_labels as $type => $label): ?>
                                <option value="<?php echo $type; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3 d-none possible-values-section" id="possibleValuesSection-addFieldModal">
                        <label class="form-label"><?php echo $lang['LBL_POSSIBLE_VALUES_HELP'] ?? 'Possible Values (one per line, drag to reorder)'; ?></label>
                        <ul class="list-group possible-values-list" data-input="possibleValuesInput-addFieldModal"></ul>
                        <input type="hidden" name="possible_values" id="possibleValuesInput-addFieldModal" value="">
                        <div class="input-group mt-2">
                            <input type="text" class="form-control add-value-input" placeholder="<?php echo $lang['PLACEHOLDER_ADD_VALUE'] ?? 'Add value...'; ?>">
                            <button type="button" class="btn btn-outline-secondary add-value-btn"><?php echo $lang['BUTTON_ADD'] ?? 'Add'; ?></button>
                        </div>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="required" id="required-addFieldModal" value="1">
                        <label class="form-check-label" for="required-addFieldModal"><?php echo $lang['STATUS_REQUIRED'] ?? 'Required'; ?></label>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_active" id="isActive-addFieldModal" value="1">
                        <label class="form-check-label" for="isActive-addFieldModal"><?php echo $lang['STATUS_ENABLED'] ?? 'Enabled'; ?></label>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo $lang['TABLE_HEADER_ORDER'] ?? 'Order'; ?></label>
                        <input type="number" class="form-control" name="sort_order" value="0" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                    <button type="submit" name="add_field" class="btn btn-primary"><?php echo $lang['ADMIN_CUSTOM_FIELDS_BTN_ADD'] ?? 'Add Field'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
function updatePossibleValuesInput(modalId) {
    var list = $('#possibleValuesSection-' + modalId + ' .possible-values-list');
    var values = [];
    list.children('li').each(function() {
        values.push($(this).find('span.flex-grow-1').text());
    });
    $('#possibleValuesInput-' + modalId).val(values.join(','));
}

$(document).ready(function() {
    // Show/hide possible values section based on type
    $('.field-type-select').on('change', function() {
        var modalId = $(this).data('modal');
        var val = $(this).val();
        var section = $('#possibleValuesSection-' + modalId);
        if (val === 'checkboxes' || val === 'select' || val === 'radio') {
            section.removeClass('d-none');
        } else {
            section.addClass('d-none');
        }
    }).trigger('change');

    // Add value
    $('.add-value-btn').on('click', function() {
        var section = $(this).closest('.possible-values-section');
        var list = section.find('.possible-values-list');
        var input = section.find('.add-value-input');
        var value = input.val().trim();
        if (value) {
            var li = $('<li class="list-group-item d-flex align-items-center"><span class="flex-grow-1"></span><button type="button" class="btn btn-sm btn-outline-danger ms-2 remove-value-btn">&times;</button></li>');
            li.find('span').text(value);
            list.append(li);
            input.val('');
            updatePossibleValuesInput(list.data('input').replace('Input-', ''));
        }
    });
    // Remove value
    $(document).on('click', '.remove-value-btn', function() {
        var list = $(this).closest('.possible-values-list');
        $(this).closest('li').remove();
        updatePossibleValuesInput(list.data('input').replace('Input-', ''));
    });
    // Make possible values sortable
    $('.possible-values-list').sortable({
        update: function(event, ui) {
            updatePossibleValuesInput($(this).data('input').replace('Input-', ''));
        }
    });

    // Ensure possible_values is up to date before submitting Add/Edit forms
    $('#addFieldModal form').on('submit', function() {
        updatePossibleValuesInput('addFieldModal');
    });
    <?php foreach ($fields as $field): ?>
    $('#editFieldModal<?php echo $field['id']; ?> form').on('submit', function() {
        updatePossibleValuesInput('editFieldModal<?php echo $field['id']; ?>');
    });
    <?php endforeach; ?>
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?> 