<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author Daniele Termini
 * @package Application\Admin
 */

namespace Application\Admin\Form;

/**
 * @deprecated
 */
class ChecklistManyToManyField extends ChecklistField
{
    /**
     *
     */
    protected $relations;

    /**
     *
     */
    public function deleteRelations()
    {
        $relations_class = $this->get('through');
        $attribute_key = $this->getAttributeKey();

        $relations = $relations_class::all([
            'conditions' => [$attribute_key . ' = ?', $this->model->id],
        ]);

        foreach ($relations as $relation) {
            $relation->delete();
        }
    }

    /**
     *
     */
    public function setRelations(array $foreigns)
    {
        $that = $this;

        $relation_class = $this->get('through');
        $model = $this->model;

        $relation_class::transaction(function () use ($that, $foreigns, $relation_class, $model): void {
            $that->deleteRelations();

            foreach ($foreigns as $foreign_id) {
                $attribute_key = $that->getAttributeKey();
                $foreign_key = $that->getForeignKey();

                $relation_class::create([
                    $attribute_key => $model->id,
                    $foreign_key   => $foreign_id,
                ]);
            }
        });
    }

    /**
     *
     */
    public function getRelations()
    {
        if ($this->relations === null) {
            $foreign_class = $this->get('foreign');
            $relations_class = $this->get('through');
            $attribute_key = $this->getAttributeKey();
            $foreign_key = $this->getForeignKey();

            $options = [
                'joins'      => 'LEFT JOIN ' . $relations_class::tableName() . ' AS r ON `from`.id = r.' . $foreign_key,
                'conditions' => ["r.{$attribute_key} = ?", $this->model->id],
            ];

            $this->relations = [];
            foreach ($foreign_class::all($options) as $relation) {
                $this->relations[$relation->id] = $relation;
            }
        }

        return $this->relations;
    }

    /**
     *
     */
    public function getAttributeKey()
    {
        $relations_class = $this->get('through');
        $primary_key = $relations_class::primaryKey();
        $attribute_key = is_array($primary_key) ? $primary_key[0] : $primary_key;

        return ($this->get('attribute_key') ?: $attribute_key);
    }

    /**
     *
     */
    public function getForeignKey()
    {
        $relations_class = $this->get('through');
        $primary_key = $relations_class::primaryKey();
        $attribute_key = is_array($primary_key) ? $primary_key[1] : $primary_key;

        return ($this->get('foreign_key') ?: $attribute_key);
    }
}
