<?php
namespace Incoviba\Controller\API\Ventas;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Controller\API\withJson;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service;

class Promotions
{
    use withJson;

    public function add(ServerRequestInterface $request, ResponseInterface $response,
                        Service\Venta\Promotion $promotionService): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'input' => $input,
            'promotions' => [],
            'success' => false,
            'partial' => false,
            'errors' => [],
        ];
        if (is_string($input['promotions'])) {
            $input['promotions'] = json_decode($input['promotions'], true);
        }
        foreach ($input['promotions'] as $promotion) {
            try {
                $promotionData = json_decode($promotion, true);
                $promotion = $promotionService->add($promotionData);
                $output['promotions'] []= [
                    'promotion' => $promotion,
                    'success' => true,
                ];
                $output['partial'] = true;
            } catch (ServiceAction\Create $exception) {
                $output['errors'] []= $this->parseError($exception);
            }
        }
        if (count($output['promotions']) == count($input['promotions'])) {
            $output['success'] = true;
        }

        return $this->withJson($response, $output);
    }
    public function edit(ServerRequestInterface $request, ResponseInterface $response,
                         Service\Venta\Promotion $promotionService): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'input' => $input,
            'promotions' => [],
            'success' => false,
            'partial' => false,
            'errors' => [],
        ];
        if (is_string($input['promotions'])) {
            $input['promotions'] = json_decode($input['promotions'], true);
        }
        foreach ($input['promotions'] as $promotion) {
            try {
                $promotionData = json_decode($promotion, true);
                $promotion = $promotionService->getById($promotionData['id']);
                unset($promotionData['id']);
                $promotion = $promotionService->edit($promotion, $promotionData);
                $output['promotions'] []= [
                    'promotion' => $promotion,
                    'success' => true,
                ];
                $output['partial'] = true;
            } catch (ServiceAction\Read | ServiceAction\Update $exception) {
                $output['errors'] []= $this->parseError($exception);
            }
        }
        if (count($output['promotions']) == count($input['promotions'])) {
            $output['success'] = true;
        }

        return $this->withJson($response, $output);
    }
    public function remove(ServerRequestInterface $request, ResponseInterface $response,
                           Service\Venta\Promotion $promotionService, int $promotion_id): ResponseInterface
    {
        $output = [
            'promotion_id' => $promotion_id,
            'promotion' => null,
            'success' => false,
            'errors' => [],
        ];
        try {
            $output['promotion'] = $promotionService->remove($promotion_id);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }

        return $this->withJson($response, $output);
    }
    public function addConnections(ServerRequestInterface $request, ResponseInterface $response,
                                   LoggerInterface $logger,
                                   Service\Venta\Promotion $promotionService, int $promotion_id): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'promotion_id' => $promotion_id,
            'input' => $input,
            'connections' => [],
            'success' => false,
            'partial' => false
        ];
        $total = 0;
        if (count($input['project']) > 0 and $input['project'][0] !== '') {
            $project_ids = array_filter($input['project'], function($project_id) { return $project_id !== ''; });
            $total += count($project_ids);
            foreach ($project_ids as $project_id) {
                try {
                    $promotionService->addProject($promotion_id, $project_id);
                    $output['connections'] []= [
                        'project_id' => $project_id,
                        'success' => true,
                    ];
                    $output['partial'] = true;
                } catch (ServiceAction\Create $exception) {
                    $logger->error($exception);
                }
            }
        }
        if (count($input['broker']) > 0 and $input['broker'][0] !== '') {
            $broker_ruts = array_filter($input['broker'], function($broker_rut) { return $broker_rut !== ''; });
            $total += count($broker_ruts);
            foreach ($broker_ruts as $broker_rut) {
                try {
                    $promotionService->addBroker($promotion_id, $broker_rut);
                    $output['connections'] []= [
                        'broker_rut' => $broker_rut,
                        'success' => true,
                    ];
                    $output['partial'] = true;
                } catch (ServiceAction\Create $exception) {
                    $logger->error($exception);
                }
            }
        }
        if (count($input['unit_type']) > 0 and $input['unit_type'][0] !== '') {
            $unit_type_ids = array_filter($input['unit_type'], function($unit_type_id) { return $unit_type_id !== ''; });
            $total += count($unit_type_ids);
            foreach ($unit_type_ids as $unit_type_id) {
                try {
                    $promotionService->addUnitType($promotion_id, $input['type_project'], $unit_type_id);
                    $output['connections'] []= [
                        'unit_type_id' => $unit_type_id,
                        'success' => true,
                    ];
                    $output['partial'] = true;
                } catch (ServiceAction\Create $exception) {
                    $logger->error($exception);
                }
            }
        }
        if (count($input['line']) > 0 and $input['line'][0] !== '') {
            $line_ids = array_filter($input['line'], function($line_id) { return $line_id !== ''; });
            $total += count($line_ids);
            foreach ($line_ids as $line_id) {
                try {
                    $promotionService->addUnitLine($promotion_id, $line_id);
                    $output['connections'] []= [
                        'line_id' => $line_id,
                        'success' => true,
                    ];
                    $output['partial'] = true;
                } catch (ServiceAction\Create $exception) {
                    $logger->error($exception);
                }
            }
        }
        if (count($input['unit']) > 0 and $input['unit'][0] !== '') {
            $unit_ids = array_filter($input['unit'], function($unit_id) { return $unit_id !== ''; });
            $total += count($unit_ids);
            foreach ($unit_ids as $unit_id) {
                try {
                    $promotionService->addUnit($promotion_id, $unit_id);
                    $output['connections'] []= [
                        'unit_id' => $unit_id,
                        'success' => true,
                    ];
                    $output['partial'] = true;
                } catch (ServiceAction\Create $exception) {
                    $logger->error($exception);
                }
            }
        }

        if (count($output['connections']) === $total) {
            $output['success'] = true;
        }

        return $this->withJson($response, $output);
    }
    public function removeProject(ServerRequestInterface $request, ResponseInterface $response,
                                  Service\Venta\Promotion $promotionService,
                                  int $promotion_id, int $project_id): ResponseInterface
    {
        $output = [
            'promotion_id' => $promotion_id,
            'project_id' => $project_id,
            'success' => false,
        ];
        try {
            $promotionService->removeProject($promotion_id, $project_id);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
    public function removeBroker(ServerRequestInterface $request, ResponseInterface $response,
                                  Service\Venta\Promotion $promotionService,
                                  int $promotion_id, string $broker_rut): ResponseInterface
    {
        $output = [
            'promotion_id' => $promotion_id,
            'broker_rut' => $broker_rut,
            'success' => false,
        ];
        try {
            $promotionService->removeBroker($promotion_id, $broker_rut);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
    public function removeUnitType(ServerRequestInterface $request, ResponseInterface $response,
                                  Service\Venta\Promotion $promotionService,
                                  int $promotion_id, int $project_id, int $unit_type_id): ResponseInterface
    {
        $output = [
            'promotion_id' => $promotion_id,
            'project_id' => $project_id,
            'unit_type_id' => $unit_type_id,
            'success' => false,
        ];
        try {
            $promotionService->removeUnitType($promotion_id, $project_id, $unit_type_id);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
    public function removeUnitLine(ServerRequestInterface $request, ResponseInterface $response,
                                  Service\Venta\Promotion $promotionService,
                                  int $promotion_id, int $unit_line_id): ResponseInterface
    {
        $output = [
            'promotion_id' => $promotion_id,
            'unit_line_id' => $unit_line_id,
            'success' => false,
        ];
        try {
            $promotionService->removeUnitLine($promotion_id, $unit_line_id);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
    public function removeUnit(ServerRequestInterface $request, ResponseInterface $response,
                              Service\Venta\Promotion $promotionService,
                              int $promotion_id, int $unit_id): ResponseInterface
    {
        $output = [
            'promotion_id' => $promotion_id,
            'unit_id' => $unit_id,
            'success' => false,
        ];
        try {
            $promotionService->removeUnit($promotion_id, $unit_id);
            $output['success'] = true;
        } catch (ServiceAction\Delete $exception) {
            return $this->withError($response, $exception);
        }
        return $this->withJson($response, $output);
    }
}
