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

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

$allowed_pages = [
    'privacy.php' => 'Privacy Policy',
    'about.php' => 'About Us',
    'services.php' => 'Services',
    'portfolio.php' => 'Portfolio',
    'terms.php' => 'Terms and Conditions',
];

$selected_file = isset($_GET['file']) ? $_GET['file'] : 'privacy.php';
$success_message = '';
$error_message = '';

if (!array_key_exists($selected_file, $allowed_pages)) {
    $selected_file = 'privacy.php';
}

function extract_page_content($full_content) {
    $start = strpos($full_content, '<!-- PAGE_CONTENT_START -->');
    $end = strpos($full_content, '<!-- PAGE_CONTENT_END -->');
    if ($start === false || $end === false || $end < $start) return '';
    $start += strlen('<!-- PAGE_CONTENT_START -->');
    return trim(substr($full_content, $start, $end - $start));
}

function replace_page_content($full_content, $new_content) {
    $start = strpos($full_content, '<!-- PAGE_CONTENT_START -->');
    $end = strpos($full_content, '<!-- PAGE_CONTENT_END -->');
    if ($start === false || $end === false || $end < $start) return $full_content;
    $start += strlen('<!-- PAGE_CONTENT_START -->');
    return substr($full_content, 0, $start)
        . "\n" . $new_content . "\n"
        . substr($full_content, $end);
}

// Validate and secure file path
$file_path = __DIR__ . '/../' . $selected_file;
// Security: Validate file path is within application root and matches whitelist
$real_file_path = realpath($file_path);
$app_root = realpath(__DIR__ . '/..');
$allowed_file_path = realpath(__DIR__ . '/../' . $selected_file);

// Security check: ensure file is within allowed directory and matches whitelist
if ($real_file_path === false || $app_root === false || 
    strpos($real_file_path, $app_root) !== 0 || 
    !in_array(basename($real_file_path), array_keys($allowed_pages))) {
    error_log("Security: Invalid file path attempted in admin/pages.php: " . htmlspecialchars($selected_file, ENT_QUOTES, 'UTF-8'));
    $selected_file = 'privacy.php'; // Reset to default
    $file_path = __DIR__ . '/../' . $selected_file;
}

$current_content = '';
$editor_content = '';
if (file_exists($file_path)) {
    $current_content = file_get_contents($file_path);
    $editor_content = extract_page_content($current_content);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_page'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $error_message = $lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'];
    } else {
        $file_to_save = $_POST['page_file'];
        $content = $_POST['page_content'];
        
        // Security: Validate file name against whitelist
        if (!array_key_exists($file_to_save, $allowed_pages)) {
            error_log("Security: Invalid page file attempted in admin/pages.php: " . htmlspecialchars($file_to_save, ENT_QUOTES, 'UTF-8'));
            $error_message = 'Invalid page file.';
        } else {
            // Security: Validate file path is within application root
            $file_path = __DIR__ . '/../' . $file_to_save;
            $real_file_path = realpath($file_path);
            $app_root = realpath(__DIR__ . '/..');
            
            // Security check: ensure file is within allowed directory
            if ($real_file_path === false || $app_root === false || 
                strpos($real_file_path, $app_root) !== 0 || 
                basename($real_file_path) !== $file_to_save) {
                error_log("Security: Path traversal attempt detected in admin/pages.php: " . htmlspecialchars($file_to_save, ENT_QUOTES, 'UTF-8'));
                $error_message = 'Invalid file path. Security violation detected.';
            } else {
            $backup_path = __DIR__ . '/../backups/pages/';
            if (!is_dir($backup_path)) {
                mkdir($backup_path, 0755, true);
            }
                // Security: Validate backup path is within allowed directory
                $backup_path = __DIR__ . '/../backups/pages/';
                $real_backup_path = realpath($backup_path);
                if ($real_backup_path === false || strpos($real_backup_path, $app_root) !== 0) {
                    error_log("Security: Invalid backup path in admin/pages.php");
                    $error_message = 'Invalid backup path. Security violation detected.';
                } else {
                    if (!is_dir($backup_path)) {
                        if (!mkdir($backup_path, 0755, true)) {
                            $error_message = 'Failed to create backup directory. Check file permissions.';
                        }
                    }
                    
                    if (empty($error_message)) {
                        $backup_file = $backup_path . basename($file_to_save) . '_' . date('Y-m-d_H-i-s') . '.backup';
                        
                        // Final security check: ensure backup file is within backup directory
                        $real_backup_file = realpath(dirname($backup_file));
                        if ($real_backup_file !== $real_backup_path) {
                            error_log("Security: Backup file path validation failed in admin/pages.php");
                            $error_message = 'Invalid backup file path. Security violation detected.';
                        } else {
                            try {
                                if (file_exists($file_path)) {
                                    copy($file_path, $backup_file);
                                }
                                $full_content = file_exists($file_path) ? file_get_contents($file_path) : '';
                                $new_full_content = replace_page_content($full_content, $content);
                                if (file_put_contents($file_path, $new_full_content) !== false) {
                                    $success_message = 'Page saved successfully. Backup created: ' . basename($backup_file);
                                    $editor_content = $content;
                                } else {
                                    $error_message = 'Failed to save page. Check file permissions.';
                                }
                            } catch (Exception $e) {
                                error_log("Error saving page in admin/pages.php: " . $e->getMessage());
                                $error_message = 'Error saving page: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
                            }
                        }
                    }
                }
            }
        }
    }
}
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2><i class="bi bi-file-earmark-text me-2"></i>Edit Site Pages</h2>
        <p class="text-muted mb-0">Edit the content of your public pages below.</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 ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo htmlspecialchars($success_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cancel"></button>
    </div>
<?php endif; ?>
<?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo htmlspecialchars($error_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cancel"></button>
    </div>
<?php endif; ?>
<form method="post" id="pageForm">
    <?php echo get_csrf_input_field(); ?>
    <input type="hidden" name="page_file" value="<?php echo htmlspecialchars($selected_file); ?>">
    <div class="card">
        <div class="card-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <label for="file_selector" class="form-label mb-0"><i class="bi bi-file-earmark me-2"></i>Select Page</label>
                    <select id="file_selector" class="form-select mt-2" onchange="changePage()">
                        <?php foreach ($allowed_pages as $file => $label): ?>
                            <option value="<?php echo htmlspecialchars($file); ?>" <?php echo $file === $selected_file ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($label . ' (' . $file . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 text-end">
                    <small class="text-muted">Currently editing: <strong><?php echo htmlspecialchars($selected_file); ?></strong></small>
                </div>
            </div>
        </div>
        <div class="card-body">
            <textarea name="page_content" id="page_content" class="form-control summernote" rows="16"><?php echo htmlspecialchars($editor_content); ?></textarea>
        </div>
        <div class="card-footer d-flex justify-content-end">
            <button type="submit" name="save_page" class="btn btn-primary">
                <i class="bi bi-floppy"></i> Save Changes
            </button>
        </div>
    </div>
</form>
<script>
function changePage() {
    var selector = document.getElementById('file_selector');
    var file = selector.value;
    window.location.href = '?file=' + encodeURIComponent(file);
}
$(document).ready(function() {
    $('.summernote').summernote({
        height: 600,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'italic', 'underline', 'clear', 'strikethrough', 'superscript', 'subscript']],
            ['fontname', ['fontname']],
            ['fontsize', ['fontsize']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['height', ['height']],
            ['table', ['table']],
            ['insert', ['link', 'hr']],
            ['view', ['fullscreen']],
        ],
        placeholder: 'Type your page content here...'
    });
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?> 