<?php

namespace auctionforge\inc\model;

use DateTime;
use auctionforge\inc\abs\Model;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\Debug;
use auctionforge\inc\InstanceDB;
use WP_Post;
use WP_Term;

class SubmissionFormData
{
    const TABLE_DATA = 'bp_submission_data';

    public static function getTableName()
    {
        $db = InstanceDB::getInstanceDB();
        return $db->prefix . self::TABLE_DATA;
    }

    /**
     * @param $data
     * @return bool|int
     */
    public static function save($data)
    {
        $db = InstanceDB::getInstanceDB();
        $tableName = self::getTableName();
        $sql = "INSERT INTO {$tableName} (`email`, `data`, `is_exported`, `ip`) VALUES ('%s', '%s', %d, '%s')";

        if ($data['email'] == '') {
            return false;
        }

        $email = $data['email'];
        unset($data['email']);

        $data = self::prepareData($data);

        $sql = $db->prepare($sql, $email, $data, 0, $_SERVER["REMOTE_ADDR"]);

        return $db->query($sql);
    }

    private static function prepareData($data)
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT);
    }

    public function getRows($page, $perPage)
    {
        $db = InstanceDB::getInstanceDB();
        $start = ($page - 1) * $perPage;
        $sql = "SELECT * FROM " . self::getTableName();

        $where = " WHERE `id` IS NOT NULL ";
        $order = "ORDER BY id DESC";

        if ($page == 0) {
            $where .= " AND `is_exported` = 0 ";
        }

        if ($perPage != -1) {
            $limit = " LIMIT " . $start . "," . $perPage;
        } else {
            $limit = "";
        }

        $sql = $sql . $where . $order . $limit;
        return $db->get_results($sql);
    }

    public function updateExportedRecords($ids)
    {
        $db = InstanceDB::getInstanceDB();
        $tableName = self::getTableName();
        $sql = "UPDATE `" . $tableName .
            "` SET `is_exported` = '1' WHERE `id` IN (" .
            implode(",", $ids) . ")";
        return $db->query($sql);
    }

    /**
     * Get the number of rows by the passed parameters
     * @param array $params
     * @return string|null
     */
    public function getCountAllRows($params = array())
    {
        $db = InstanceDB::getInstanceDB();
        $where = "";
        if (!empty($params)) {
            $where .= $this->whereFormatSql($params);
        }
        $sql = "SELECT COUNT(`id`) FROM " . self::getTableName() . " WHERE `id` IS NOT NULL > 0";
        $sql = $sql . $where;
        return $db->get_var($sql);
    }

    /**
     * Formation of a request condition
     * @param $params
     * @return string
     */
    private function whereFormatSql($params) {
        $where = "";

        return $where;
    }

    private function formatSqlForFilterDate($date) {
        $date = explode(' to ', $date);
        $where = "";
        if (!empty($date[0]) && !empty($date[1])) {
            try {
                $dateTime = new \DateTime($date[1]);
                $dateTime->modify('+1 day');
                $date[1] = $dateTime->format('Y-m-d');
            } catch (Exception $e) {
                return "";
            }
            $where .= " AND `syncDatetime` BETWEEN '" . $date[0] . "' AND '" . $date[1] . "' ";
        } elseif (!empty($date[0])) {
            $where .= " AND `syncDatetime` > '" . $date[0] . "' ";
        }
        return $where;
    }
}