<?php

namespace Core\App\Controllers;

use Core\App\Models\HomeSections;
use Core\App\Services\UploadService;
use Core\System\Response;

class HomeSectionsController
{
    private UploadService $uploads;

    public function __construct()
    {
        $this->uploads = new UploadService(ROOT_PATH . '/uploads', '/uploads');
    }

    public function index()
    {
        $sectionsModel = new HomeSections();
        view_admin('home_sections/index', ['sections' => $sectionsModel->getAll()]);
    }

    public function create()
    {
        view_admin('home_sections/create');
    }

    public function store()
    {
        $sectionType = $_POST['section_type'] ?? null;
        if (!$sectionType) {
            Response::redirect('/admin/home-sections');
        }

        $order   = (int)($_POST['section_order'] ?? 0);
        $enabled = isset($_POST['is_enabled']) ? 1 : 0;

        try {
            $settings = $this->buildSettings($sectionType, $_POST['settings'] ?? [], $_FILES);
        } catch (\RuntimeException $e) {
            $_SESSION['flash_error'] = $e->getMessage();
            Response::redirect('/admin/home-sections/create');
            return;
        }

        (new HomeSections())->add($sectionType, $order, $enabled, $settings);
        Response::redirect('/admin/home-sections');
    }

    public function edit($id)
    {
        view_admin('home_sections/edit', ['id' => (int) $id]);
    }

    public function update($id)
    {
        $sectionsModel = new HomeSections();
        $section = $sectionsModel->getById((int) $id);
        if (!$section) {
            Response::redirect('/admin/home-sections');
        }

        $order   = (int)($_POST['section_order'] ?? 0);
        $enabled = isset($_POST['is_enabled']) ? 1 : 0;

        try {
            $settings = $this->buildSettings($section['section_type'], $_POST['settings'] ?? [], $_FILES, $section['settings'] ?? []);
        } catch (\RuntimeException $e) {
            $_SESSION['flash_error'] = $e->getMessage();
            Response::redirect('/admin/home-sections/edit/' . (int)$id);
            return;
        }

        $sectionsModel->update((int) $id, $order, $enabled, $settings);
        Response::redirect('/admin/home-sections');
    }

    public function delete($id)
    {
        if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
            http_response_code(405);
            exit('Method Not Allowed');
        }

        (new HomeSections())->delete((int) $id);
        Response::redirect('/admin/home-sections');
    }

    /**
     * Re-index a multi-file $_FILES sub-array so it's always keyed by the
     * numeric index that appears in the input name (e.g. slides_images[2]).
     *
     * PHP collapses  name="foo[2]"  into  $_FILES['foo']['name'][2]  already,
     * so this helper just normalises missing keys and filters out empty slots.
     */
    private function extractFileByIndex(array $filesGroup, int $index): ?array
    {
        $name    = $filesGroup['name'][$index]    ?? '';
        $error   = $filesGroup['error'][$index]   ?? UPLOAD_ERR_NO_FILE;
        $tmpName = $filesGroup['tmp_name'][$index] ?? '';

        if ($error !== UPLOAD_ERR_OK || empty($name) || empty($tmpName)) {
            return null;
        }

        return [
            'name'     => $name,
            'type'     => $filesGroup['type'][$index]  ?? '',
            'tmp_name' => $tmpName,
            'error'    => $error,
            'size'     => $filesGroup['size'][$index]  ?? 0,
        ];
    }

    private function buildSettings(string $sectionType, array $settingsInput, array $files, array $currentSettings = []): array
    {
        $settings = [];

        // ── top_bar ──────────────────────────────────────────────────────────
        if ($sectionType === 'top_bar') {
            $messages = preg_split('/\r\n|\r|\n/', (string)($settingsInput['messages'] ?? ''));
            $settings['messages'] = array_values(array_filter(array_map('trim', $messages)));
            return $settings;
        }

        // ── hero_slider ───────────────────────────────────────────────────────
        if ($sectionType === 'hero_slider') {
            $slides       = $settingsInput['slides'] ?? [];
            $filesGroup   = $files['slides_images'] ?? [];

            foreach ($slides as $i => &$slide) {
                // Try to upload a new file for this slide index
                $fileData = !empty($filesGroup) ? $this->extractFileByIndex($filesGroup, (int)$i) : null;

                if ($fileData !== null) {
                    $uploaded = $this->uploads->storeImage($fileData, 'home/hero');
                    if ($uploaded) {
                        $slide['image'] = $uploaded;
                    }
                }
                // Keep existing image value (from hidden text input) if no new file
                $slide['image']       = trim((string)($slide['image'] ?? ''));
                $slide['title']       = trim((string)($slide['title'] ?? ''));
                $slide['subtitle']    = trim((string)($slide['subtitle'] ?? ''));
                $slide['button_text'] = trim((string)($slide['button_text'] ?? ''));
                $slide['button_url']  = trim((string)($slide['button_url'] ?? ''));
            }
            unset($slide);

            $settings['slides'] = array_values(array_filter($slides, function ($slide) {
                return !empty($slide['image'])
                    || !empty($slide['title'])
                    || !empty($slide['subtitle'])
                    || !empty($slide['button_text'])
                    || !empty($slide['button_url']);
            }));
            return $settings;
        }

        // ── products_section ─────────────────────────────────────────────────
        if ($sectionType === 'products_section') {
            $settings['title']       = trim((string)($settingsInput['title'] ?? ''));
            $settings['subtitle']    = trim((string)($settingsInput['subtitle'] ?? ''));
            $settings['source']      = $settingsInput['source'] ?? 'latest';
            $settings['category_id'] = $settings['source'] === 'category'
                ? (int)($settingsInput['category_id'] ?? 0)
                : null;
            return $settings;
        }

        // ── ads_section ───────────────────────────────────────────────────────
        if ($sectionType === 'ads_section') {
            $ads        = $settingsInput['ads'] ?? [];
            $filesGroup = $files['ads_images'] ?? [];

            foreach ($ads as $i => &$ad) {
                // Animated texts: textarea → array
                $raw = (string)($ad['animated_texts'] ?? '');
                $ad['animated_texts'] = array_values(
                    array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $raw)))
                );

                // Upload new image if provided
                $fileData = !empty($filesGroup) ? $this->extractFileByIndex($filesGroup, (int)$i) : null;
                if ($fileData !== null) {
                    $uploaded = $this->uploads->storeImage($fileData, 'home/ads');
                    if ($uploaded) {
                        $ad['image'] = $uploaded;
                    }
                }

                $ad['image']      = trim((string)($ad['image'] ?? ''));
                $ad['headline']   = trim((string)($ad['headline'] ?? ''));
                $ad['button_url'] = trim((string)($ad['button_url'] ?? '#'));
            }
            unset($ad);

            $settings['ads'] = array_values(array_filter($ads, fn($ad) => !empty($ad['image'])));
            return $settings;
        }

        // ── faq_section ───────────────────────────────────────────────────────
        if ($sectionType === 'faq_section') {
            $settings['subtitle'] = trim((string)($settingsInput['subtitle'] ?? ''));
            $items = [];
            foreach (($settingsInput['items'] ?? []) as $item) {
                $question = trim((string)($item['question'] ?? ''));
                $answer   = trim((string)($item['answer'] ?? ''));
                if ($question !== '' && $answer !== '') {
                    $items[] = ['question' => $question, 'answer' => $answer];
                }
            }
            $settings['items'] = $items;
            return $settings;
        }

        return $currentSettings;
    }
}
