<?php
// Schedule Module for Futura
class ModelCheckoutSchedule extends Model {

  public function getScheduleFromFuturaParameters() {
    $sql = "SELECT pf.is_futura FROM parametros_efutura pf;";
    $result = $this->db->query($sql);

    return $result->row['is_futura'] > 0 ?? false;
  }

  public function getScheduleByOrderID($order_id) {
    $sql = "SELECT ost.date, ost.time, os.type, os.status, os.name
            FROM " . DB_PREFIX . "order od
            INNER JOIN " . DB_PREFIX . "schedule_times ost ON od.order_id = ost.order_id
            INNER JOIN " . DB_PREFIX . "schedule os ON os.schedule_id = ost.schedule_id
            WHERE od.order_id = " . (int)$order_id;
    $results = $this->db->query($sql);

    return $results->rows;
  }

  public function getScheduleDates($data) {
    $meet_type = "'" . $this->db->escape($data['meet_type']) . "'";

    $sql = "SELECT DISTINCT ost.`date` FROM oc_schedule os
      INNER JOIN oc_schedule_times ost
      ON os.schedule_id = ost.schedule_id
      WHERE os.`status` = 1 
              AND os.`type` = " . $meet_type . 
            " AND ost.`date` >= CURDATE()";

    $results = $this->db->query($sql);

    $response = [];
    foreach ($results->rows as $row) {
      $response[] = $row['date'];
    }

    return $response;
  }

  public function getScheduleTimes($data) {
    $data['meet_date'] = implode( '-', array_reverse( explode( '/', $data['meet_date'] ) ) );

    $meet_type = "'" . $this->db->escape($data['meet_type']) . "'";
    $meet_date = "'" . $this->db->escape($data['meet_date']) . "'";

    $sql = "SELECT DISTINCT TIME_FORMAT(ost.`time`, '%H:%i' ) AS `time` FROM oc_schedule os
              INNER JOIN oc_schedule_times ost
              ON os.schedule_id = ost.schedule_id
                WHERE os.`status` = 1
                  AND os.`type` = " . $meet_type .
                " AND ost.`date` = " . $meet_date .
                " AND ost.`order_id` IS NULL 
                  AND (ost.`date` > CURDATE() OR (ost.`date` = CURDATE() AND ost.`time` >= CURTIME()))
            ORDER BY ost.`time` ASC";

    $results = $this->db->query($sql);

    $response = [];
    foreach ($results->rows as $row) {
      $response[] = $row['time'];
    }

    return $response;
  }

  public function setOrderScheduled($data) {

    $data['meet_date'] = implode( '-', array_reverse( explode( '/', $data['meet_date'] ) ) );

    $meet_type = $this->db->escape($data['meet_type']);
    $meet_date = $this->db->escape($data['meet_date']);
    $meet_time = $this->db->escape($data['meet_time']);
    $order_id = $this->db->escape($data['order_id']);

    if (empty($order_id) || empty($meet_type) || empty($meet_date) || empty($meet_time)) {
      return [
        'type' => 'warning',
        'message' => 'Os dados de agendamento estão incompletos. Verifique ou contate-nos!',
      ];
    }

    $sql = "SELECT os.`schedule_id` FROM oc_schedule os
            INNER JOIN oc_schedule_times ost ON os.schedule_id = ost.schedule_id
            WHERE os.`status` = 1
            AND os.`type` = '$meet_type'
            AND ost.`date` = '$meet_date'
            AND ost.`time` = '$meet_time'
            AND ost.`order_id` IS NULL";

    $results = $this->db->query($sql);

    $resultsID = [];
    foreach ($results->rows as $row) {
      $resultsID[] = $row['schedule_id'];
    }

    if (empty($resultsID)) {
      return [
        'type' => 'warning',
        'message' => 'Não foi possível encontrar um agendamento disponível. Contate-nos!',
      ];
    }

    $scheduleID = count($resultsID) > 1 ? $resultsID[array_rand($resultsID)] : $resultsID[0];

    $sql = "UPDATE oc_schedule_times ost
            SET ost.`order_id` = $order_id
            WHERE schedule_id = $scheduleID
            AND ost.`date` = '$meet_date'
            AND ost.`time` = '$meet_time'
            AND ost.`order_id` IS NULL;";

    $result = $this->db->query($sql);

    return $result ? [
      'type' => 'success',
      'message' => 'Agendamento realizado com sucesso!',
    ] : [
      'type' => 'warning',
      'message' => 'Não foi possível realizar o agendamento. Contate-nos!',
    ];
  }

  public function setOrderScheduledCanceled($data) {

    if (empty($data['order_id'])) {
      return [
        'type' => 'warning',
        'message' => 'Não foi possível realizar o cancelamento! Contate-nos!',
      ];
    }

    $sql = "UPDATE oc_schedule_times ost
            SET ost.`order_id` = NULL
            where order_id = " . $data['order_id'] . ";";

    $result = $this->db->query($sql);

    return $result ? [
      'type' => 'success',
      'message' => 'Agendamento cancelado com sucesso!',
    ] : [
      'type' => 'warning',
      'message' => 'Não foi possível realizar o cancelamento! Contate-nos!',
    ];
  }

  public function hasLinkTicketCertificate($order_id) {
    $sql = "SELECT * FROM ". DB_PREFIX . "ticket_certificate WHERE order_id = '" . $order_id . "' ";

    $results = $this->db->query($sql);

    return $results->rows;
  }

  public function hasScheduledOrder($order_id) {
    $sql = "SELECT * FROM oc_schedule_times ost
    WHERE ost.`order_id` = $order_id";

    $result = $this->db->query($sql);
    return count($result->rows) > 0 ?? false;
  }
}

