<?php

namespace Core\App\Controllers;

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

class ProductPageBuilderController
{
    protected ProductSections $sections;

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

    public function save($productId)
    {
        $layout = Request::input('layout');

        if (!is_array($layout)) {
            return Response::redirect('/admin/products/edit/' . $productId);
        }

        // Remove old layout
        \db()->prepare(
            "DELETE FROM product_sections WHERE product_id = ?"
        )->execute([$productId]);

        // Insert new layout
        foreach ($layout as $order => $section) {
            \db()->prepare("
                INSERT INTO product_sections
                (product_id, section_type, section_order, is_enabled, settings)
                VALUES (?, ?, ?, ?, ?)
            ")->execute([
                $productId,
                $section['type'],
                $order,
                $section['enabled'] ?? 1,
                json_encode($section['settings'] ?? [])
            ]);
        }

        return Response::redirect('/admin/products/edit/' . $productId . '?saved=1');
    }
}
