<?php
class ControllerModulePagseguroAbandoned extends Controller {
  public function index() {
    $language = $this->load->language('module/pagseguro_abandoned');
    $this->data = array_merge($this->data, $language);

    $this->document->setTitle($this->language->get('heading_title'));
    $this->document->addScript('admin/public/js/module/pagseguro_abandoned.js');

    $token = $this->session->data['token'];
    $this->data['token'] = $token;

    $this->data['breadcrumbs'] = [
      [
        'text' => $this->language->get('text_home'),
        'href' => $this->url->link('common/home', 'token=' . $token, 'SSL'),
      ],
      [
        'text' => $this->language->get('text_module'),
        'href' => $this->url->linkAnchor('extension/module', 'token=' . $token, 'tab-info=' . $this->request->get['type'], 'SSL'),
      ],
      [
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('module/pagseguro_abandoned', 'token=' . $token . '&type=' . $this->request->get['type'], 'SSL'),
      ]
    ];

    $url_back = $this->url->linkAnchor(
      'extension/module',
      'token=' . $token,
      'tab-info=' . $this->request->get['type'],
      'SSL'
    );

    $url_action = $this->url->link(
      'module/pagseguro_abandoned/execute',
      'token=' . $token . '&type=' . $this->request->get['type'],
      'SSL'
    );

    $url_pagseguro_abandoned = $this->url->link('payment/pagseguro_abandoned','','SSL');

    $this->data['data'] = [
      'action' => str_replace('&amp;', '&', $url_action),
      'back' => str_replace('&amp;', '&', $url_back),
      'pagseguroAbandoned' => str_replace('/admin/', '/', $url_pagseguro_abandoned)
    ];

    $this->children = [
      'common/header',
      'common/footer',
    ];

    $this->response->setOutput($this->render('module/pagseguro_abandoned'));
  }

  public function execute() {
    $language = $this->load->language('module/pagseguro_abandoned');
    $this->data = array_merge($this->data, $language);

    $response = [];

    // if (!$this->user->hasPermission('modify', 'module/pagseguro')) {
    //   $response['warning'] = $this->language->get('error_permission');
    //   return $this->response->setOutputJson($response);
    // }

    $erros = $this->validate();
    if ($erros) {
      $response['errors'] = $erros;
      return $this->response->setOutputJson($response);
    }

    $this->load->dmodel("checkout/order");
    extract($this->request->post);

    $date_initial = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $date_initial)));
    $date_ended = date('Y-m-d 23:59:59', strtotime(str_replace('/', '-', $date_ended)));
   
    $response['success'] = $this->language->get('text_success');
    
    $orders = $this->dmodel_checkout_order->updateAbandonedOrdersPagseguro(null, $date_initial, $date_ended);
    if (!$orders) {
      $response = ['errors' => ["Erro ao atualizar os pedidos abandonados."]];
    }

    $abandonedOrders = $this->dmodel_checkout_order->getAbandonedOrdersPagseguro($date_initial, $date_ended);
    if ($abandonedOrders) {
      foreach ($abandonedOrders as $order) {
        $checkoutData = $this->dmodel_checkout_order->getPagSeguroCheckoutFromOrderOtherInfos($order['order_id']);
        if ($checkoutData && isset($checkoutData['checkout_id']) && isset($checkoutData['checkout_status']) && !in_array($checkoutData['checkout_status'], ['EXPIRED', 'CANCELED', 'INACTIVE'])) {
          $this->pagseguro->inactivateCheckout($checkoutData['checkout_id']);
        }
      }
    }

    return $this->response->setOutputJson($response);
  }

  private function validate() {
    extract($this->request->post);

    return $this->validate->execute([
      'date_initial' => [
        'value' => $date_initial,
        'validates' => ['isEmpty'],
      ],
      'date_ended' => [
        'value' => $date_ended,
        'validates' => ['isEmpty'],
      ],
    ]);
  }
}
