<?php
/**
 * ITSWEBER CMS – Page Section Model
 *
 * Represents a placed section instance in the page builder.
 * Each row is one section on a page (e.g. homepage).
 *
 * @author    Benny Weber (ITSWEBER)
 * @copyright © ITSWEBER – www.itsweber.de
 * @contact   kontakt@itsweber.de
 */

namespace App\Models;

use App\Core\Model;

class PageSection extends Model
{
    protected static string $table = 'iw_page_sections';

    /**
     * Get all active sections for a given page context, ordered by sort_order.
     */
    public static function active(string $context = 'homepage'): array
    {
        return static::where(['page_context' => $context, 'is_active' => 1], 'sort_order', 'ASC');
    }

    /**
     * Get all sections (active + inactive) for a given page context.
     */
    public static function byContext(string $context = 'homepage'): array
    {
        return static::where(['page_context' => $context], 'sort_order', 'ASC');
    }

    /**
     * Count sections of a specific type within a page context.
     */
    public static function countByType(string $typeKey, string $context = 'homepage'): int
    {
        return static::count(['page_context' => $context, 'section_type' => $typeKey]);
    }

    /**
     * Get the next sort_order value for a page context.
     */
    public static function nextSortOrder(string $context = 'homepage'): int
    {
        $max = static::db()->fetchColumn(
            "SELECT COALESCE(MAX(sort_order), 0) FROM " . static::$table . " WHERE page_context = :ctx",
            ['ctx' => $context]
        );
        return (int) $max + 1;
    }

    /**
     * Update sort_order for multiple sections at once.
     * Expects an array of section IDs in the desired order.
     */
    public static function reorder(array $ids): void
    {
        $order = 0;
        foreach ($ids as $id) {
            static::updateById((int) $id, ['sort_order' => $order]);
            $order++;
        }
    }

    /**
     * Duplicate a section. Returns the new section ID.
     */
    public static function duplicate(int $id): ?int
    {
        $original = static::find($id);
        if (!$original) {
            return null;
        }

        $newOrder = static::nextSortOrder($original['page_context']);

        return static::create([
            'page_context'   => $original['page_context'],
            'section_type'   => $original['section_type'],
            'instance_label' => $original['instance_label']
                ? $original['instance_label'] . ' (Kopie)'
                : null,
            'content'        => $original['content'],
            'is_active'      => 0, // Duplicates start inactive
            'sort_order'     => $newOrder,
        ]);
    }
}
