<?php
namespace Incoviba\Repository\Venta;

use PDO;
use PDOException;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository\Proyecto\Broker;

class Promotion extends Common\Ideal\Repository
{
    public function __construct(Common\Define\Connection $connection, protected Broker\Contract $contractRepository, protected Precio $precioRepository)
    {
        parent::__construct($connection);
    }

    public function getTable(): string
    {
        return 'promotions';
    }

    public function create(?array $data = null): Model\Venta\Promotion
    {
        $map = (new Common\Implement\Repository\MapperParser(['description', 'amount']))
            ->register('type', (new Common\Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return Model\Venta\Promotion\Type::from($data['type']);
                }))
            ->register('state', (new Common\Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return Model\Venta\Promotion\State::from($data['state']);
                })
                ->setDefault(Model\Venta\Promotion\State::ACTIVE))
            ->register('start_date', new Common\Implement\Repository\Mapper\DateTime('start_date', 'startDate'))
            ->register('end_date', (new Common\Implement\Repository\Mapper\DateTime('end_date', 'endDate'))
                ->setDefault(null))
            ->register('valid_until', (new Common\Implement\Repository\Mapper\DateTime('valid_until', 'validUntil'))
                ->setDefault(null));

        return $this->parseData(new Model\Venta\Promotion(), $data, $map);
    }

    public function save(Common\Define\Model $model): Model\Venta\Promotion
    {
        $model->id = $this->saveNew(
            ['description', 'amount', 'type', 'start_date', 'end_date', 'valid_until'],
            [$model->description, $model->amount, $model->type->value, $model->startDate->format('Y-m-d'),
                $model->endDate?->format('Y-m-d'), $model->validUntil?->format('Y-m-d')]
        );
        return $model;
    }
    public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Promotion
    {
        return $this->update($model, ['description', 'amount', 'type', 'start_date', 'end_date', 'valid_until'], $new_data);
    }

    public function filterData(array $data): array
    {
        $filteredData = array_intersect_key($data, array_flip(['description', 'amount', 'type', 'start_date', 'end_date', 'valid_until']));
        if (!isset($filteredData['amount']) and isset($data['value'])) {
            $filteredData['amount'] = $data['value'];
        }
        $filteredData['type'] = (int) $filteredData['type'];
        if ($filteredData['amount'] > 1 and $filteredData['type'] === Model\Venta\Promotion\Type::VARIABLE->value) {
            $filteredData['amount'] = $filteredData['amount'] / 100;
        }
        return $filteredData;
    }

    /**
     * @param int $contract_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByContract(int $contract_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_brokers pb ON pb.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc ON bc.broker_rut = pb.broker_rut')
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc2 ON bc2.project_id = pp.project_id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc3 ON bc3.project_id = put.project_id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
            ->joined('LEFT OUTER JOIN broker_contracts bc4 ON bc4.project_id = ptu.proyecto')
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.id = unidad.pt')
            ->joined('LEFT OUTER JOIN broker_contracts bc5 ON bc5.project_id = ptu2.proyecto')
            ->where('bc.id = :contract_id OR bc2.id = :contract_id OR bc3.id = :contract_id OR bc4.id = :contract_id OR bc5.id = :contract_id')
            ->group('a.id');
        return $this->fetchMany($query, ['contract_id' => $contract_id]);
    }

    /**
     * @param int $contract_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchActiveByContract(int $contract_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_broker pb ON pb.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc ON bc.id = pb.contract_id')
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc2 ON bc2.project_id = pp.project_id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc3 ON bc3.project_id = put.project_id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
            ->joined('LEFT OUTER JOIN broker_contracts bc4 ON bc4.project_id = btu.proyecto')
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.id = unidad.pt')
            ->joined('LEFT OUTER JOIN broker_contracts bc5 ON bc5.project_id = ptu2.proyecto')
            ->where('(bc.id = :contract_id OR bc2.id = :contract_id OR bc3.id = :contract_id OR bc4.id = :contract_id OR bc5.id = :contract_id) AND a.state = :state')
            ->group('a.id');
        return $this->fetchMany($query, ['contract_id' => $contract_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
    }

    /**
     * @param int $unit_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByUnit(int $unit_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
            ->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
            ->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = pul.unit_line_id')
            ->where('pu.unit_id = :unit_id OR u1.id = :unit_id OR u2.id = :unit_id OR u3.id = :unit_id')
            ->group('a.id');
        return $this->fetchMany($query, ['unit_id' => $unit_id]);
    }

    /**
     * @param int $unit_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchActiveByUnit(int $unit_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
            ->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
            ->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = pul.unit_line_id')
            ->where('(pu.unit_id = :unit_id OR u1.id = :unit_id OR u2.id = :unit_id OR u3.id = :unit_id) AND a.state = :state')
            ->group('a.id');
        return $this->fetchMany($query, ['unit_id' => $unit_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
    }

    /**
     * @param int $project_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByProject(int $project_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu.id = unidad.pt')
            ->where('pp.project_id = :project_id OR put.project_id = :project_id OR ptu.proyecto = :project_id OR ptu1.proyecto = :project_id')
            ->group('a.id');
        return $this->fetchMany($query, ['project_id' => $project_id]);
    }

    /**
     * @param int $project_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchActiveByProject(int $project_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu ON ptu.id = pul.unit_line_id')
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN unidad ON unidad.id = pu.unit_id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu.id = unidad.pt')
            ->where('(pp.project_id = :project_id OR put.project_id = :project_id OR ptu.proyecto = :project_id OR ptu1.proyecto = :project_id) AND a.state = :state')
            ->group('a.id');
        return $this->fetchMany($query, ['project_id' => $project_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
    }

    /**
     * @param int $contract_id
     * @param int $unit_id
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByContractAndUnit(int $contract_id, int $unit_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_brokers pb ON pb.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc ON bc.broker_rut = pb.broker_rut')
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
            ->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
            ->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu3 ON ptu3.id = pul.unit_line_id')
            ->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = ptu3.id')
            ->where('bc.id = :contract_id OR pu.unit_id = :unit_id OR u1.id = :unit_id OR u2.id = :unit_id OR u3.id = :unit_id')
            ->group('a.id');
        return $this->fetchMany($query, ['contract_id' => $contract_id, 'unit_id' => $unit_id]);
    }

    /**
     * @param int $contract_id
     * @param array $unit_ids
     * @return array
     * @throws Common\Implement\Exception\EmptyResult
     */
    public function fetchByContractAndUnits(int $contract_id, array $unit_ids): array
    {
        $interrogations = implode(',', array_map(fn($k) => ":id{$k}", array_keys($unit_ids)));
        $query = $this->connection->getQueryBuilder()
            ->select('DISTINCT a.*, GROUP_CONCAT(COALESCE(pu.unit_id, u1.id, u2.id, u3.id) SEPARATOR "|") as unit_id')
            ->from("{$this->getTable()} a")
            ->joined('LEFT OUTER JOIN promotion_brokers pb ON pb.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN broker_contracts bc ON bc.broker_rut = pb.broker_rut')
            ->joined('LEFT OUTER JOIN promotion_units pu ON pu.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN promotion_projects pp ON pp.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu1 ON ptu1.proyecto = pp.project_id')
            ->joined('LEFT OUTER JOIN unidad u1 ON u1.pt = ptu1.id')
            ->joined('LEFT OUTER JOIN promotion_unit_types put ON put.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu2 ON ptu2.tipo = put.unit_type_id AND ptu2.proyecto = put.project_id')
            ->joined('LEFT OUTER JOIN unidad u2 ON u2.pt = ptu2.id')
            ->joined('LEFT OUTER JOIN promotion_unit_lines pul ON pul.promotion_id = a.id')
            ->joined('LEFT OUTER JOIN proyecto_tipo_unidad ptu3 ON ptu3.id = pul.unit_line_id')
            ->joined('LEFT OUTER JOIN unidad u3 ON u3.pt = ptu3.id')
            ->where("bc.id = :contract_id OR pu.unit_id IN ({$interrogations}) OR u1.id IN ({$interrogations}) OR u2.id IN ({$interrogations}) OR u3.id IN ({$interrogations})")
            ->group('a.id');
        $unitParams = array_combine(array_map(fn($k) => "id{$k}", array_keys($unit_ids)), $unit_ids);
        try {
            $results = $this->connection->execute($query, array_merge(['contract_id' => $contract_id], $unitParams))->fetchAll(PDO::FETCH_ASSOC);
            if (empty($results)) {
                throw new Common\Implement\Exception\EmptyResult($query);
            }
            $temp = new class()
            {
                protected array $promotions = [];
                public function addItem(int $id, Model\Venta\Promotion $promotion): void
                {
                    if (!array_key_exists($id, $this->promotions)) {
                        $this->promotions[$id] = [
                            'id' => $id,
                            'promotions' => []
                        ];
                    }
                    $this->promotions[$id]['promotions'] []= $promotion;
                }
                public function toArray(): array
                {
                    return array_values($this->promotions);
                }
            };
            foreach ($results as $result) {
                if (str_contains($result['unit_id'], '|')) {
                    $ids = explode('|', $result['unit_id']);
                    foreach ($ids as $id) {
                        $temp->addItem((int) $id, $this->load($result));
                    }
                    continue;
                }
                $temp->addItem((int) $result['unit_id'], $this->load($result));
            }
            return $temp->toArray();
        } catch (PDOException $exception) {
            throw new Common\Implement\Exception\EmptyResult($query, $exception);
        }
    }

    /**
     * @param Model\Venta\Promotion $promotion
     * @param int $project_id
     * @return void
     * @throws PDOException
     */
    public function insertProjectForPromotion(Model\Venta\Promotion $promotion, int $project_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->insert()
            ->into('promotion_projects')
            ->columns(['promotion_id', 'project_id'])
            ->values([':promotion_id', ':project_id']);
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'project_id' => $project_id]);
    }
    public function removeProjectForPromotion(Model\Venta\Promotion $promotion, int $project_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->delete()
            ->from('promotion_projects')
            ->where('promotion_id = :promotion_id AND project_id = :project_id');
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'project_id' => $project_id]);
    }

    /**
     * @param Model\Venta\Promotion $promotion
     * @param int $broker_rut
     * @return void
     * @throws PDOException
     */
    public function insertBrokerForPromotion(Model\Venta\Promotion $promotion, int $broker_rut): void
    {
        $query = $this->connection->getQueryBuilder()
            ->insert()
            ->into('promotion_brokers')
            ->columns(['promotion_id', 'broker_rut'])
            ->values([':promotion_id', ':broker_rut']);
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'broker_rut' => $broker_rut]);
    }
    public function removeBrokerForPromotion(Model\Venta\Promotion $promotion, int $broker_rut): void
    {
        $query = $this->connection->getQueryBuilder()
            ->delete()
            ->from('promotion_brokers')
            ->where('promotion_id = :promotion_id AND broker_rut = :broker_rut');
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'broker_rut' => $broker_rut]);
    }

    /**
     * @param Model\Venta\Promotion $promotion
     * @param int $project_id
     * @param int $unit_type_id
     * @return void
     */
    public function insertUnitTypeForPromotion(Model\Venta\Promotion $promotion, int $project_id, int $unit_type_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->insert()
            ->into('promotion_unit_types')
            ->columns(['promotion_id', 'project_id', 'unit_type_id'])
            ->values([':promotion_id', ':project_id', ':unit_type_id']);
        $this->connection->execute($query,
            ['promotion_id' => $promotion->id, 'project_id' => $project_id, 'unit_type_id' => $unit_type_id]);
    }
    public function removeUnitTypeForPromotion(Model\Venta\Promotion $promotion, int $project_id, int $unit_type_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->delete()
            ->from('promotion_unit_types')
            ->where('promotion_id = :promotion_id AND project_id = :project_id AND unit_type_id = :unit_type_id');
        $this->connection->execute($query,
            ['promotion_id' => $promotion->id, 'project_id' => $project_id, 'unit_type_id' => $unit_type_id]);
    }

    /**
     * @param Model\Venta\Promotion $promotion
     * @param int $unit_line_id
     * @return void
     */
    public function insertUnitLineForPromotion(Model\Venta\Promotion $promotion, int $unit_line_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->insert()
            ->into('promotion_unit_lines')
            ->columns(['promotion_id', 'unit_line_id'])
            ->values([':promotion_id', ':unit_line_id']);
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_line_id' => $unit_line_id]);
    }
    public function removeUnitLineForPromotion(Model\Venta\Promotion $promotion, int $unit_line_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->delete()
            ->from('promotion_unit_lines')
            ->where('promotion_id = :promotion_id AND unit_line_id = :unit_line_id');
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_line_id' => $unit_line_id]);
    }

    /**
     * @param Model\Venta\Promotion $promotion
     * @param int $unit_id
     * @return void
     */
    public function insertUnitForPromotion(Model\Venta\Promotion $promotion, int $unit_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->insert()
            ->into('promotion_units')
            ->columns(['promotion_id', 'unit_id'])
            ->values([':promotion_id', ':unit_id']);
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_id' => $unit_id]);
    }
    public function removeUnitForPromotion(Model\Venta\Promotion $promotion, int $unit_id): void
    {
        $query = $this->connection->getQueryBuilder()
            ->delete()
            ->from('promotion_units')
            ->where('promotion_id = :promotion_id AND unit_id = :unit_id');
        $this->connection->execute($query, ['promotion_id' => $promotion->id, 'unit_id' => $unit_id]);
    }
}
