<?php
/**
 * SmartThink3 LMS - Edit Site Content Block
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/SiteContent.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$siteContent = new SiteContent();
$db = Database::getInstance();

$errors = [];
$success = false;
$block = null;

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id > 0) {
    $block = $siteContent->getBlockById($id);
    if (!$block) {
        $_SESSION['flash']['danger'] = 'Content block not found.';
        header('Location: site_content.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pageSlug    = trim($_POST['page_slug'] ?? '');
    $blockKey    = trim($_POST['block_key'] ?? '');
    $label       = trim($_POST['label'] ?? '');
    $region      = trim($_POST['region'] ?? 'global');
    $contentType = trim($_POST['content_type'] ?? 'text');
    $content     = $_POST['content'] ?? '';

    if ($pageSlug === '') {
        $errors[] = 'Page slug is required.';
    }
    if ($blockKey === '') {
        $errors[] = 'Block key is required.';
    }

    $allowedRegions = ['global', 'usa', 'europe', 'africa'];
    if (!in_array($region, $allowedRegions, true)) {
        $errors[] = 'Invalid region selected.';
    }

    $allowedTypes = ['text', 'html', 'json'];
    if (!in_array($contentType, $allowedTypes, true)) {
        $errors[] = 'Invalid content type selected.';
    }

    if (empty($errors)) {
        try {
            $userId = function_exists('getCurrentUserId') ? getCurrentUserId() : null;
            $siteContent->saveBlock($pageSlug, $blockKey, $content, $label, $region, $contentType, $userId);
            $_SESSION['flash']['success'] = 'Content block saved successfully.';
            header('Location: site_content.php?page=' . urlencode($pageSlug));
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (!$block && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Defaults for new block
    $block = [
        'page_slug'    => $_GET['page'] ?? '',
        'block_key'    => $_GET['key'] ?? '',
        'label'        => '',
        'region'       => 'global',
        'content_type' => 'text',
        'content'      => '',
    ];
}

$pageTitle = $id > 0 ? 'Edit Content Block' : 'Add Content Block';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h4 mb-0"><?php echo htmlspecialchars($pageTitle); ?></h1>
        <p class="text-muted mb-0">Define content for a specific page and block key.</p>
    </div>
    <div>
        <a href="site_content.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Back to Site Content
        </a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul class="mb-0">
            <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <form method="post" action="" data-validate="1">
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="page_slug" class="form-label">Page Slug</label>
                    <input type="text" name="page_slug" id="page_slug" class="form-control" required value="<?php echo htmlspecialchars($_POST['page_slug'] ?? ($block['page_slug'] ?? '')); ?>" placeholder="e.g. home, about, services">
                    <div class="form-text">Used by templates, e.g. <code>home</code>, <code>about</code>, <code>services</code>.</div>
                </div>
                <div class="col-md-4">
                    <label for="block_key" class="form-label">Block Key</label>
                    <input type="text" name="block_key" id="block_key" class="form-control" required value="<?php echo htmlspecialchars($_POST['block_key'] ?? ($block['block_key'] ?? '')); ?>" placeholder="e.g. hero_title, hero_subtitle">
                    <div class="form-text">A unique key within the page, used in code.</div>
                </div>
                <div class="col-md-4">
                    <label for="label" class="form-label">Label (Admin Only)</label>
                    <input type="text" name="label" id="label" class="form-control" value="<?php echo htmlspecialchars($_POST['label'] ?? ($block['label'] ?? '')); ?>" placeholder="e.g. Home Hero Title">
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="region" class="form-label">Region</label>
                    <select name="region" id="region" class="form-select">
                        <?php
                        $regions = ['global' => 'Global (default)', 'usa' => 'USA', 'europe' => 'Europe', 'africa' => 'Africa'];
                        $currentRegion = $_POST['region'] ?? ($block['region'] ?? 'global');
                        foreach ($regions as $value => $labelText): ?>
                            <option value="<?php echo htmlspecialchars($value); ?>" <?php echo $currentRegion === $value ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($labelText); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="content_type" class="form-label">Content Type</label>
                    <select name="content_type" id="content_type" class="form-select">
                        <?php
                        $types = ['text' => 'Plain Text', 'html' => 'HTML', 'json' => 'JSON'];
                        $currentType = $_POST['content_type'] ?? ($block['content_type'] ?? 'text');
                        foreach ($types as $value => $labelText): ?>
                            <option value="<?php echo htmlspecialchars($value); ?>" <?php echo $currentType === $value ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($labelText); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="mb-3">
                <label for="content" class="form-label">Content</label>
                <textarea name="content" id="content" rows="10" class="form-control" data-editor="tinymce"><?php echo htmlspecialchars($_POST['content'] ?? ($block['content'] ?? '')); ?></textarea>
                <div class="form-text">Use plain text or HTML depending on the content type chosen.</div>
            </div>

            <div class="d-flex justify-content-end gap-2">
                <a href="site_content.php" class="btn btn-outline-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary" data-loading="1">
                    <i class="fas fa-save me-2"></i>Save Content
                </button>
            </div>
        </form>
    </div>
</div>

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