<?php
// admin/assistant.php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


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

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

$allowedTabs = ['general', 'features', 'style'];
$editableSettings = array_filter($lang_config['ADMIN_SETTINGS_EDITOR_CONFIG'], function($key) use ($allowedTabs) {
    return in_array(strtolower($key), $allowedTabs);
}, ARRAY_FILTER_USE_KEY);

function getCurrentValue($constant) {
    if (defined($constant)) {
        $value = constant($constant);
        if ($constant === 'CUSTOM_JAVASCRIPT_CODE' && !empty($value)) {
            $decoded = base64_decode($value, true);
            if ($decoded !== false) {
                return $decoded;
            }
        }
        return $value;
    }
    return '';
}

function formatArrayForDisplay($array) {
    if (!is_array($array)) {
        return is_string($array) ? $array : '';
    }
    return implode(', ', $array);
}

function updateConfigValue($configContent, $key, $value, $type, $isArray = false) {
    global $lang_alerts;
    $result = [
        'content' => $configContent,
        'updated' => false,
        'error' => ''
    ];
    if ($isArray) {
        if (is_string($value)) {
            $value = array_map('trim', explode(',', $value));
        }
        $value = array_filter($value);
        
        // Format as PHP array - preserve associative structure if needed
        if (is_array($value) && count($value) > 0) {
            $arrayElements = [];
            foreach ($value as $k => $v) {
                if (is_numeric($k)) {
                    // Indexed array
                    $arrayElements[] = "'" . addslashes($v) . "'";
                } else {
                    // Associative array
                    $arrayElements[] = "'" . addslashes($k) . "' => '" . addslashes($v) . "'";
                }
            }
            $formattedValue = "[" . implode(", ", $arrayElements) . "]";
        } else {
            $formattedValue = "[]"; // Empty array
        }
    } else if ($type === 'boolean') {
        $formattedValue = $value ? 'true' : 'false';
    } else if ($type === 'number') {
        $formattedValue = (int) $value;
    } else {
        $formattedValue = "'" . addslashes($value) . "'";
    }
    if ($isArray) {
        // For arrays, match define with array syntax (handles both indexed and associative arrays)
        $pattern = "/define\\s*\\(\\s*(['\"])$key\\1\\s*,\\s*\\[.*?\\]\\s*\\)\\s*;/s";
    } else if ($type === 'boolean') {
        $pattern = "/define\\s*\\(\\s*(['\"])$key\\1\\s*,\\s*(true|false|[01])\\s*\\)\\s*;/i";
    } else if ($type === 'number') {
        // For numbers, match define with numeric values including decimals
        $pattern = "/define\\s*\\(\\s*(['\"])$key\\1\\s*,\\s*[\\d\\.\\s\\*\\/\\+\\-]+\\s*\\)\\s*;/i";
    } else if ($key === 'TIMEZONE') {
        if (!in_array($value, DateTimeZone::listIdentifiers())) {
            $result['error'] = $lang_alerts['ALERT_SETTINGS_INVALID_TIMEZONE'];
            return $result;
        }
        $pattern = "/define\\s*\\(\\s*(['\"])$key\\1\\s*,\\s*(['\"]).*?\\2\\s*\\)\\s*;/s";
    } else {
        $pattern = "/define\\s*\\(\\s*(['\"])$key\\1\\s*,\\s*(['\"]).*?\\2\\s*\\)\\s*;/s";
    }
    $newContent = preg_replace($pattern, "define('$key', $formattedValue);", $configContent, 1, $count);
    if ($newContent === null) {
        $result['error'] = sprintf($lang_alerts['ALERT_SETTINGS_REGEX_ERROR'], $key);
        return $result;
    }
    if ($count === 0) {
        // Constant not found, try to add it at the end of the file
        // Find the last define statement and add our new one after it
        if (preg_match("/define\\s*\\(\\s*(['\"])[A-Z_]+\\1.*?\\)\\s*;/s", $configContent, $matches, PREG_OFFSET_CAPTURE)) {
            $lastDefinePos = $matches[0][1] + strlen($matches[0][0]);
            $newDefine = "\ndefine('$key', $formattedValue);";
            $newContent = substr_replace($configContent, $newDefine, $lastDefinePos, 0);
            $count = 1;
        } else {
            // Couldn't find any define statements, append before closing PHP tag or at end
            if (preg_match("/\\?\\>\\s*$/", $configContent)) {
                // Has closing PHP tag, insert before it
                $newContent = preg_replace("/(\\?\\>\\s*)$/", "\ndefine('$key', $formattedValue);\n$1", $configContent);
            } else {
                // No closing tag, append to end of file
                $newContent = $configContent . "\ndefine('$key', $formattedValue);";
            }
            $count = 1;
        }
    }
    $result['content'] = $newContent;
    $result['updated'] = $count > 0;
    return $result;
}

$formSubmitted = false;
$formSuccess = false;
$formErrors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_settings'])) {
    $formSubmitted = true;
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $formErrors[] = $lang_alerts['ALERT_SETTINGS_INVALID_CSRF'];
    } else {
        $configFile = __DIR__ . '/../config/config.php';
        if (!is_readable($configFile)) {
            $formErrors[] = $lang_alerts['ALERT_SETTINGS_CONFIG_NOT_READABLE'];
        } elseif (!is_writable($configFile)) {
            $formErrors[] = $lang_alerts['ALERT_SETTINGS_CONFIG_NOT_WRITABLE'];
        } else {
            $configContent = file_get_contents($configFile);
            if ($configContent === false) {
                $formErrors[] = $lang_alerts['ALERT_SETTINGS_CONFIG_READ_FAILED'];
            } else {
                $changes = 0;
                $updateLog = [];
                $newConfigContent = $configContent;
                foreach ($editableSettings as $section => $settings) {
                    foreach ($settings as $key => $setting) {
                        if ($key === 'BASE_URL') continue;
                        if (isset($setting['readonly']) && $setting['readonly']) continue;
                        if ($setting['type'] === 'boolean') {
                            $newValue = isset($_POST[$key]) ? true : false;
                            $updateResult = updateConfigValue(
                                $newConfigContent,
                                $key,
                                $newValue,
                                $setting['type']
                            );
                        } elseif (isset($_POST[$key])) {
                            $processedValue = $_POST[$key];
                            if ($key === 'CUSTOM_JAVASCRIPT_CODE') {
                                $processedValue = preg_replace('/<\/?script[^>]*>/i', '', $processedValue);
                                $processedValue = trim($processedValue);
                                if (!empty($processedValue)) {
                                    $processedValue = base64_encode($processedValue);
                                }
                            }
                            $updateResult = updateConfigValue(
                                $newConfigContent,
                                $key,
                                $processedValue,
                                $setting['type'],
                                isset($setting['is_array']) && $setting['is_array']
                            );
                        } else {
                            continue;
                        }
                        if (!empty($updateResult['error'])) {
                            $formErrors[] = $updateResult['error'];
                        } else if ($updateResult['updated']) {
                            $newConfigContent = $updateResult['content'];
                            $changes++;
                            $updateLog[] = sprintf($lang_admin['ADMIN_SETTINGS_LOG_UPDATED'], $setting['label'], $key);
                        }
                    }
                }
                $setupResult = updateConfigValue(
                    $newConfigContent,
                    'SETUP_DONE',
                    true,
                    'boolean'
                );
                if (!empty($setupResult['error'])) {
                    $formErrors[] = $setupResult['error'];
                } elseif ($setupResult['updated']) {
                    $newConfigContent = $setupResult['content'];
                    $changes++;
                    $updateLog[] = 'SETUP_DONE set to true';
                }
                if ($changes > 0 && empty($formErrors)) {
                    if (file_put_contents($configFile, $newConfigContent) !== false) {
                        $formSuccess = true;
                        if (function_exists('opcache_reset')) {
                            opcache_reset();
                        }
                        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SETTINGS_UPDATE_SUCCESS'], 'success');
                        if (!headers_sent()) {
                            header("Location: " . getCleanUrl('admin/assistant'));
                            exit;
                        } else {
                            echo '<script>window.location.href="' . getCleanUrl('admin/assistant') . '";</script>';
                            echo sprintf($lang_admin['ADMIN_SETTINGS_REDIRECT_FALLBACK'], getCleanUrl('admin/assistant'));
                            exit;
                        }
                    } else {
                        $formErrors[] = $lang_alerts['ALERT_SETTINGS_CONFIG_WRITE_FAILED'];
                    }
                } elseif (empty($formErrors) && $changes == 0) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SETTINGS_NO_CHANGES'], 'info');
                }
            }
        }
    }
}
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1">Assistant to setup the main features</h2>
        <p class="text-muted mb-0">Follow the steps of this assistant to setup the main features and content of SupportEngine.</p>
    </div>
    <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
        <i class="bi bi-arrow-left"></i> Back to Dashboard
    </a>
</div>
<?php if (!empty($formErrors)): ?>
<div class="alert alert-danger">
    <h5><?php echo $lang_admin['ADMIN_SETTINGS_ERROR_OCCURRED_TITLE']; ?></h5>
    <ul>
        <?php foreach ($formErrors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>
<div class="card">
    <div class="card-body">
        <form action="<?php echo getCleanUrl('admin/assistant'); ?>" method="post" id="assistantForm">
            <?php echo get_csrf_input_field(); ?>
            <input type="hidden" name="update_settings" value="1">
            <div id="assistantStepper">
                <div class="stepper-header d-flex mb-4">
                    <?php $stepIndex = 0; $totalSteps = count($editableSettings); ?>
                    <?php foreach ($editableSettings as $sectionKey => $section): ?>
                        <div class="flex-fill text-center stepper-step" data-step="<?php echo $stepIndex; ?>">
                            <div class="step-circle" id="step-circle-<?php echo $stepIndex; ?>"><?php echo $stepIndex + 1; ?></div>
                            <div class="step-label small"><?php echo ucwords(str_replace('_', ' ', $sectionKey)); ?></div>
                        </div>
                        <?php if ($stepIndex < $totalSteps - 1): ?>
                            <div class="stepper-line"></div>
                        <?php endif; ?>
                        <?php $stepIndex++; ?>
                    <?php endforeach; ?>
                </div>
                <div class="stepper-content">
                    <?php $stepIndex = 0; ?>
                    <?php foreach ($editableSettings as $sectionKey => $section): ?>
                        <div class="step-pane" id="step-pane-<?php echo $stepIndex; ?>" style="display:<?php echo $stepIndex === 0 ? 'block' : 'none'; ?>;">
                            <div class="row">
                                <?php 
                                $sectionKeys = array_keys($section);
                                $leftColumnKeys = array_slice($sectionKeys, 0, ceil(count($sectionKeys) / 2));
                                $rightColumnKeys = array_slice($sectionKeys, ceil(count($sectionKeys) / 2));
                                ?>
                                <div class="col-md-6">
                                    <?php foreach ($leftColumnKeys as $key): ?>
                                        <?php $setting = $section[$key]; ?>
                                        <?php
                                        $display_style = '';
                                        if (isset($setting['depends_on'])) {
                                            $dependency_key = $setting['depends_on'];
                                            if (!getCurrentValue($dependency_key)) {
                                                $display_style = 'style="display:none;"';
                                            }
                                        }
                                        if ($display_style === '' && isset($setting['depends_on_setting'])) {
                                            $dependency_setting_key = $setting['depends_on_setting'];
                                            if (!getCurrentValue($dependency_setting_key)) {
                                                $display_style = 'style="display:none;"';
                                            }
                                        }
                                        ?>
                                        <div class="mb-3 <?php echo isset($setting['data_smtp_field']) && $setting['data_smtp_field'] ? 'smtp-field' : ''; ?>" <?php echo $display_style; ?>>
                                            <label for="<?php echo $key; ?>" class="form-label">
                                                <?php echo htmlspecialchars($setting['label']); ?>
                                            </label>
                                            <?php
                                            $currentValue = getCurrentValue($key);
                                            if (isset($setting['value']) && isset($setting['readonly'])) {
                                                $displayValue = $setting['value'];
                                            } else {
                                                $displayValue = $currentValue;
                                            }
                                            if ($setting['type'] === 'boolean'):
                                                $shouldDisplay = true;
                                                if (($key === 'ALLOW_USER_TASKS' || $key === 'ENABLE_KANBAN_VIEW' || $key === 'ENABLE_FILES') && defined('ENABLE_PROJECTS') && !ENABLE_PROJECTS) {
                                                    $shouldDisplay = false;
                                                }
                                            ?>
                                                <div class="form-check form-switch" <?php echo !$shouldDisplay ? 'style="display:none;"' : ''; ?>>
                                                    <input type="checkbox" class="form-check-input" role="switch"
                                                           id="<?php echo $key; ?>"
                                                           name="<?php echo $key; ?>"
                                                           value="1" <?php echo $currentValue ? 'checked' : ''; ?> />
                                                    <label class="form-check-label text-dark" for="<?php echo $key; ?>">
                                                    </label>
                                                </div>
                                            <?php elseif ($setting['type'] === 'file'): ?>
                                                <input type="file" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" />
                                            <?php elseif (isset($setting['is_array']) && $setting['is_array']): ?>
                                                <input type="text" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars(formatArrayForDisplay($displayValue)); ?>" />
                                            <?php elseif ($setting['type'] === 'select'): ?>
                                                <select class="form-select" id="<?php echo $key; ?>" name="<?php echo $key; ?>">
                                                    <?php
                                                    $options = is_callable($setting['options']) ? call_user_func($setting['options']) : $setting['options'];
                                                    foreach ($options as $value => $label): ?>
                                                        <option value="<?php echo htmlspecialchars($value); ?>" <?php echo $currentValue == $value ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($label); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            <?php elseif ($setting['type'] === 'password'): ?>
                                                <input type="password" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars((string)$displayValue); ?>" <?php echo isset($setting['readonly']) && $setting['readonly'] ? 'readonly' : ''; ?> />
                                            <?php elseif ($setting['type'] === 'textarea'): ?>
                                                <textarea class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" rows="<?php echo isset($setting['rows']) ? (int)$setting['rows'] : 5; ?>" <?php echo isset($setting['readonly']) && $setting['readonly'] ? 'readonly' : ''; ?>><?php echo htmlspecialchars((string)$displayValue); ?></textarea>
                                            <?php else: ?>
                                                <input type="<?php echo htmlspecialchars($setting['type']); ?>" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars((string)$displayValue); ?>" <?php echo isset($setting['readonly']) && $setting['readonly'] ? 'readonly' : ''; ?> />
                                            <?php endif; ?>
                                            <small class="form-text text-muted"><?php echo $setting['description']; ?></small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <div class="col-md-6">
                                    <?php foreach ($rightColumnKeys as $key): ?>
                                        <?php $setting = $section[$key]; ?>
                                        <?php
                                        $display_style = '';
                                        if (isset($setting['depends_on'])) {
                                            $dependency_key = $setting['depends_on'];
                                            if (!getCurrentValue($dependency_key)) {
                                                $display_style = 'style="display:none;"';
                                            }
                                        }
                                        if ($display_style === '' && isset($setting['depends_on_setting'])) {
                                            $dependency_setting_key = $setting['depends_on_setting'];
                                            if (!getCurrentValue($dependency_setting_key)) {
                                                $display_style = 'style="display:none;"';
                                            }
                                        }
                                        ?>
                                        <div class="mb-3 <?php echo isset($setting['data_smtp_field']) && $setting['data_smtp_field'] ? 'smtp-field' : ''; ?>" <?php echo $display_style; ?>>
                                            <label for="<?php echo $key; ?>" class="form-label">
                                                <?php echo htmlspecialchars($setting['label']); ?>
                                            </label>
                                            <?php
                                            $currentValue = getCurrentValue($key);
                                            if (isset($setting['value']) && isset($setting['readonly'])) {
                                                $displayValue = $setting['value'];
                                            } else {
                                                $displayValue = $currentValue;
                                            }
                                            if ($setting['type'] === 'boolean'):
                                                $shouldDisplay = true;
                                                if (($key === 'ALLOW_USER_TASKS' || $key === 'ENABLE_KANBAN_VIEW' || $key === 'ENABLE_FILES') && defined('ENABLE_PROJECTS') && !ENABLE_PROJECTS) {
                                                    $shouldDisplay = false;
                                                }
                                            ?>
                                                <div class="form-check form-switch" <?php echo !$shouldDisplay ? 'style="display:none;"' : ''; ?>>
                                                    <input type="checkbox" class="form-check-input" role="switch"
                                                           id="<?php echo $key; ?>"
                                                           name="<?php echo $key; ?>"
                                                           value="1" <?php echo $currentValue ? 'checked' : ''; ?> />
                                                    <label class="form-check-label text-dark" for="<?php echo $key; ?>">
                                                    </label>
                                                </div>
                                            <?php elseif ($setting['type'] === 'file'): ?>
                                                <input type="file" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" />
                                            <?php elseif (isset($setting['is_array']) && $setting['is_array']): ?>
                                                <input type="text" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars(formatArrayForDisplay($displayValue)); ?>" />
                                            <?php elseif ($setting['type'] === 'select'): ?>
                                                <select class="form-select" id="<?php echo $key; ?>" name="<?php echo $key; ?>">
                                                    <?php
                                                    $options = is_callable($setting['options']) ? call_user_func($setting['options']) : $setting['options'];
                                                    foreach ($options as $value => $label): ?>
                                                        <option value="<?php echo htmlspecialchars($value); ?>" <?php echo $currentValue == $value ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($label); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            <?php elseif ($setting['type'] === 'password'): ?>
                                                <input type="password" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars((string)$displayValue); ?>" <?php echo isset($setting['readonly']) && $setting['readonly'] ? 'readonly' : ''; ?> />
                                            <?php elseif ($setting['type'] === 'textarea'): ?>
                                                <textarea class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" rows="<?php echo isset($setting['rows']) ? (int)$setting['rows'] : 5; ?>" <?php echo isset($setting['readonly']) && $setting['readonly'] ? 'readonly' : ''; ?>><?php echo htmlspecialchars((string)$displayValue); ?></textarea>
                                            <?php else: ?>
                                                <input type="<?php echo htmlspecialchars($setting['type']); ?>" class="form-control" id="<?php echo $key; ?>" name="<?php echo $key; ?>" value="<?php echo htmlspecialchars((string)$displayValue); ?>" <?php echo isset($setting['readonly']) && $setting['readonly'] ? 'readonly' : ''; ?> />
                                            <?php endif; ?>
                                            <small class="form-text text-muted"><?php echo $setting['description']; ?></small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary stepper-prev" <?php echo $stepIndex === 0 ? 'style="display:none;"' : ''; ?>>Previous</button>
                                <button type="button" class="btn btn-primary stepper-next" <?php echo $stepIndex === $totalSteps - 1 ? 'style="display:none;"' : ''; ?>>Next</button>
                                <?php if ($stepIndex === $totalSteps - 1): ?>
                                    <button type="submit" class="btn btn-success ms-auto">Apply Now</button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php $stepIndex++; ?>
                    <?php endforeach; ?>
                </div>
            </div>
        </form>
    </div>
</div>
<style>
.stepper-header { gap: 0.5rem; }
.stepper-step { position: relative; }
.step-circle { width: 36px; height: 36px; border-radius: 50%; background: #0d6efd; color: #fff; display: inline-flex; align-items: center; justify-content: center; font-weight: bold; margin-bottom: 0.25rem; margin-left: auto; margin-right: auto; }
.step-label { margin-top: 0.25rem; }
.stepper-line { flex: 1 1 0; height: 2px; background: #dee2e6; align-self: center; margin: 0 0.25rem; }
.step-pane { animation: fadeIn 0.2s; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var currentStep = 0;
    var totalSteps = <?php echo count($editableSettings); ?>;
    var panes = document.querySelectorAll('.step-pane');
    var stepCircles = document.querySelectorAll('.step-circle');
    var prevBtns = document.querySelectorAll('.stepper-prev');
    var nextBtns = document.querySelectorAll('.stepper-next');
    function showStep(idx) {
        panes.forEach(function(pane, i) { pane.style.display = (i === idx) ? 'block' : 'none'; });
        stepCircles.forEach(function(circle, i) { circle.style.background = (i === idx) ? '#0d6efd' : '#dee2e6'; circle.style.color = (i === idx) ? '#fff' : '#212529'; });
    }
    prevBtns.forEach(function(btn, i) {
        btn.addEventListener('click', function() {
            if (currentStep > 0) { currentStep--; showStep(currentStep); }
        });
    });
    nextBtns.forEach(function(btn, i) {
        btn.addEventListener('click', function() {
            if (currentStep < totalSteps - 1) { currentStep++; showStep(currentStep); }
        });
    });
    showStep(currentStep);
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?> 