<?php

namespace Core\App\Controllers;

use Core\App\Models\ThemeSections;
use Core\System\Request;
use Core\System\Response;

class ThemeSectionsController
{
    protected $sections;
    protected array $manifest;

    public function __construct()
    {
        $this->sections = new ThemeSections();

        // Load Section Manifest
        $this->manifest = require ROOT_PATH . '/core/config/sections.php';
    }

    /**
     * Display all editable sections only
     */
    public function index()
    {
        $allSections = $this->sections->getAll();
        $editableSections = [];

        foreach ($allSections as $section) {
            $key = $section['section_key'] ?? null;

            if (
                $key &&
                isset($this->manifest[$key]) &&
                ($this->manifest[$key]['editable'] ?? false) === true
            ) {
                $section['definition'] = $this->manifest[$key];
                $editableSections[] = $section;
            }
        }

        view_admin('theme_sections/index', [
            'sections' => $editableSections,
            'manifest' => $this->manifest,
        ]);
    }

    /**
     * Show edit page for a section
     */
    public function edit($id)
    {
        $section = $this->sections->getById((int)$id);

        if (!$section) {
            return Response::redirect('/admin/appearance/sections');
        }

        $key = $section['section_key'] ?? null;

        if (!$key || !isset($this->manifest[$key])) {
            return Response::redirect('/admin/appearance/sections');
        }

        $definition = $this->manifest[$key];

        if (($definition['editable'] ?? false) !== true) {
            return Response::redirect('/admin/appearance/sections');
        }

        view_admin('theme_sections/edit', [
            'section'    => $section,
            'definition' => $definition,
        ]);
    }

    /**
     * Save edited section
     */
    public function update($id)
    {
        $data = Request::input();

        $payload = [];

        if (isset($data['section_order'])) {
            $payload['section_order'] = (int)$data['section_order'];
        }

        if (isset($data['settings']) && is_array($data['settings'])) {
            $payload['settings'] = array_map(
                fn ($v) => is_string($v) ? trim($v) : $v,
                $data['settings']
            );
        }

        if (!empty($payload)) {
            $this->sections->update((int)$id, $payload);
        }

        return Response::redirect('/admin/appearance/sections');
    }

    /**
     * Create a new section (only from manifest)
     */
    public function create()
    {
        $available = [];

        foreach ($this->manifest as $key => $def) {
            if (($def['editable'] ?? false) === true) {
                $available[$key] = $def;
            }
        }

        view_admin('theme_sections/create', [
            'available_sections' => $available,
        ]);
    }

    /**
     * Store new section
     */
    public function store()
    {
        $data = Request::input();
        $key  = $data['section_key'] ?? null;

        if (
            !$key ||
            !isset($this->manifest[$key]) ||
            ($this->manifest[$key]['editable'] ?? false) !== true
        ) {
            return Response::redirect('/admin/appearance/sections');
        }

        // ✅ التعديل الوحيد هنا: ترتيب البراميترات
        $this->sections->add(
            $key, // section_key
            $key, // section_type (template file)
            (int)($data['section_order'] ?? 0),
            [],   // settings (array)
            1     // is_enabled (int)
        );

        return Response::redirect('/admin/appearance/sections');
    }

    /**
     * Delete a section
     */
    public function delete($id)
    {
        $this->sections->delete((int)$id);

        return Response::redirect('/admin/appearance/sections');
    }
}
