<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: SEOPageType.php,v 1.3.2.2 2026/01/09 15:16:01 rtigero Exp $

namespace Pmb\SEO\Models;

use Pmb\Common\Helper\Helper;
use Pmb\Common\Models\Model;
use Pmb\Common\Helper\Portal;
use Pmb\SEO\Orm\SEOPageTypeOrm;

class SEOPageType extends Model
{
    protected $ormName = "Pmb\SEO\Orm\SEOPageTypeOrm";

    public $idPageType = 0;
    public $type = 0;
    public $indexable = false;
    public $followable = false;

    /*
    * Retourne les donnees necessaires pour la vue
    * @return array
    */
    public static function getData() {
        $portal = new Portal();

        $defaultIPageIndexingRules = $portal::DEFAULT_PAGE_INDEXING_RULES;
        $pages = $portal::PAGES;

        $data = [
            'pageTypes' => [],
            'pageTypesLabel' => []
        ];

        // Indexer les types de page existants en BDD par leur type
        $SEOPageTypesDb = [];
        foreach(SEOPageTypeOrm::findAll() as $orm) {
            $SEOPageTypesDb[$orm->type] = $orm;
        }

        foreach($defaultIPageIndexingRules as $typeLabel => $rules) {
            $type = intval($pages[$typeLabel]);

            // Si le type existe en BDD, on utilise ses valeurs
            if(isset($SEOPageTypesDb[$type])) {
                $SEOPageType = new SEOPageType($SEOPageTypesDb[$type]->{SEOPageTypeOrm::$idTableName});
            } else {
                // Sinon on utilise les valeurs par defaut
                $SEOPageType = new SEOPageType();
                $SEOPageType->type = $type;
                $SEOPageType->indexable = $rules['indexable'];
                $SEOPageType->followable = $rules['followable'];
            }

            $data['pageTypes'][$type] = Helper::toArray($SEOPageType);
            $data['pageTypesLabel'][$type] = $portal::getLabel($type);
        }

        return $data;
    }

    /*
    * Set les donnees a partir d'un objet
    * @param object $data
    * @return void
    */
    public function setFromForm(object $data)
    {
        $this->type = $data->type;
        $this->indexable = intval($data->indexable);
        $this->followable = intval($data->followable);
    }

    /*
    * Cree un nouvel objet en base
    * @return void
    */
    public function create()
    {
        $orm = new $this->ormName($this->id);
        $orm->type = $this->type;
        $orm->indexable = $this->indexable;
        $orm->followable = $this->followable;
        $orm->save();

        $this->id = $orm->{$this->ormName::$idTableName};
    }

    /*
    * Supprime tous les objets en base
    * @return void
    */
    public static function deleteAll()
    {
        $SEOPageTypes = SEOPageTypeOrm::findAll();

        foreach ($SEOPageTypes as $SEOPageType) {
            $SEOPageType->delete();
        }
    }
}