<?php
require_once("class.db.php");
require_once("class.company.php");
require_once("class.utils.php");
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
//////////////////////////////////////////
class Setting
{

    private $restapi;
    public $company;
    public $utils;
    public $conn;

    public function __construct($restapi = null, $db_name = null)
    {
        $this->restapi = $restapi;
        $this->company = new COMPANY($restapi);
        $this->utils = new Utils();
        /////////////////////////////////////////
        if (!$this->restapi->dbutils->isDBInService()) {
            die($this->restapi->Response(["message" => "Failed to connect to the database, please try again laiter", "success" => false], 500));
        }
        ///////////////////////////////////////
        $db = new APIDB($db_name);
        $this->conn = $db->dbConnection();
    }

    ////////////////////////
    public function getUUID()
    {
        $response = new stdClass;
        $response->message = "";
        $response->uuid = $this->utils->generateUUID();
        $response->success = true;
        return $response;
    }

    public function getCompanyDBUtils($companyid)
    {
        /////////////////////////////////////////////
        $company = $this->company->getCompany($companyid);
        if (!$company["success"]) {
            die($company);
        }
        /////////////////////////////////////////////
        extract($company);
        $companyDbUtils = new DBUtils($db_name);
        return $companyDbUtils;
    }


    # Get settings group
    public function getSettingGroups($companyid)
    {
        $results = [];
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_setting_group");
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($results, $response);
        }
        return $results;
    }

    public function SettingGroupExists($companyid, $settinggroupid)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_setting_group WHERE id=:usettinggroupid");
        $stmt->bindparam(":usettinggroupid", $settinggroupid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function getSettingGroupById($companyid, $settinggroupid)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_setting_group WHERE id=:usettinggroupid");
        $stmt->bindparam(":usettinggroupid", $settinggroupid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
            return $response;
        } else {
            return array("message" => "", "success" => false);
        }
    }


    public function getGroupSettings($companyid, $object = true)
    {
        $results = array();
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_setting_group");
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settinggroupid = $response["id"];
            $code_name = $response["code_name"];
            $settings = $this->getSettingsByGroupId($companyid, $settinggroupid, $object);
            $response["settings"] = $settings;
            if ($object) {
                $results[$code_name] = $response;
            } else {
                array_push($results, $response);
            }
        }
        return $results;
    }

    public function getSettingGroupByCodeName($companyid, $code_name)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_setting_group WHERE code_name=:ucodename");
        $stmt->bindparam(":ucodename", $code_name);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
            return $response;
        } else {
            return array("message" => "Setting group doesn't exist", "success" => false);
        }
    }

    public function _initSettings()
    {
        if (!$this->restapi->utils->is_session_started()) session_start();
        if (isset($_SESSION['company']['id'])) {
            $companyid = $_SESSION['company']['id'];
            if (!empty($companyid) && !is_null($companyid)) {
                $settings = $this->getSettings(intval($companyid));
                foreach ($settings as $setting) {
                    // print_r($settings);
                    $entry_value = $setting["entry_value"];
                    $code_name = $setting["code_name"];
                    if (!defined($code_name)) define($code_name, $entry_value);
                }
            }
        } else {
            return array("message" => "Company session not initialised", "success" => false);
        }
    }
    # Get All settings
    public function getSettings($companyid, $object = true)
    {
        $results = array();
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings");
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $entry_value = $response["entry_value"];
            $is_boolean = $response["is_boolean"];
            $is_int = $response["is_int"];
            $is_float = $response["is_float"];
            $is_string = $response["is_string"];
            $code_name = $response["code_name"];
            ////////////////////////////////////
            if ($is_boolean) {
                $entry_value = $entry_value == '1' || $entry_value == 'yes' || $entry_value == 1 ? true : false;
            } else if ($is_int) {
                $entry_value = intval($entry_value);
            } else if ($is_float) {
                $entry_value = floatval($entry_value);
            } else if ($entry_value == null) {
                $entry_value = '';
            }
            $response["entry_value"] = $entry_value;
            ///////////////////////////////////////
            if ($object) {
                $results[$code_name] = $response;
            } else {
                array_push($results, $response);
            }
        }
        return $results;
    }

    # Get All settings
    public function getSettingsByGroupId($companyid, $settinggroupid, $object = true)
    {
        $results = array();
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE group_id = :usettinggroupid");
        $stmt->bindparam(":usettinggroupid", $settinggroupid);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $entry_value = $response["entry_value"];
            $is_boolean = $response["is_boolean"];
            $is_int = $response["is_int"];
            $is_float = $response["is_float"];
            $is_string = $response["is_string"];
            $code_name = $response["code_name"];
            ////////////////////////////////////
            if ($is_boolean) {
                $entry_value = $entry_value == '1' || $entry_value == 'yes' || $entry_value == 1 ? true : false;
            } else if ($is_int) {
                $entry_value = intval($entry_value);
            } else if ($is_float) {
                $entry_value = floatval($entry_value);
            } else if ($entry_value == null) {
                $entry_value = '';
            }
            $response["entry_value"] = $entry_value;
            ///////////////////////////////////////
            if ($object) {
                $results[$code_name] = $response;
            } else {
                array_push($results, $response);
            }
        }
        return $results;
    }


    # Get All settings
    public function getSettingsByGroupCodeName($companyid, $code_name, $object = true)
    {
        $group = $this->getSettingGroupByCodeName($companyid, $code_name);
        $settinggroupid = $group["id"];
        $results = array();
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE group_id = :usettinggroupid");
        $stmt->bindparam(":usettinggroupid", $settinggroupid);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $entry_value = $response["entry_value"];
            $is_boolean = $response["is_boolean"];
            $is_int = $response["is_int"];
            $is_float = $response["is_float"];
            $is_string = $response["is_string"];
            $code_name = $response["code_name"];
            ////////////////////////////////////
            if ($is_boolean) {
                $entry_value = $entry_value == '1' || $entry_value == 'yes' || $entry_value == 1 ? true : false;
            } else if ($is_int) {
                $entry_value = intval($entry_value);
            } else if ($is_float) {
                $entry_value = floatval($entry_value);
            } else if ($entry_value == null) {
                $entry_value = '';
            }
            $response["entry_value"] = $entry_value;
            ///////////////////////////////////////
            if ($object) {
                $results[$code_name] = $response;
            } else {
                array_push($results, $response);
            }
        }
        return $results;
    }


    public function SettingExists($companyid, $settingid)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE id=:usettingid");
        $stmt->bindparam(":usettingid", $settingid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            return true;
        } else {
            return false;
        }
    }


    public function _initDefaultSettings($companyid)
    {
        /////////////////////////////////////////////
        $company = $this->company->getCompany($companyid);
        /////////////////////////////////////////////////
        if (!$company["success"]) {
            die($company);
        }
        /////////////////////////////////////////////
        $uuid = $this->utils->generateUUID();
        $email = $company["email"];
        // TODO: Add default settings
        $this->UpdateSettingByCodeName($companyid, "PESAPAL_IPN_ID", $uuid);
        $this->UpdateSettingByCodeName($companyid, "PESAPAL_NOTIFICATION_EMAIL", $email);
        return array("message" => "Settings initialised successfully", "success" => true);
    }

    public function UpdateSettingById($companyid, $settingid, $entry_value)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE id=:usettingid");
        $stmt->bindparam(":usettingid", $settingid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $stmt = $dbutils->runQuery("UPDATE pm_settings SET entry_value=:uentryvalue WHERE id=:usettingid");
            $stmt->bindparam(":usettingid", $settingid);
            $stmt->bindparam(":uentryvalue", $entry_value);
            if ($stmt->execute()) {
                return array("message" => "Setting updated successfully", "success" => true);
            } else {
                return array("message" => "Something went wrong", "success" => false);
            }
        } else {
            return array("message" => "Setting doesn't exist", "success" => false);
        }
    }

    public function getSettingById($companyid, $settingid)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE id=:usettingid");
        $stmt->bindparam(":usettingid", $settingid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $entry_value = $response["entry_value"];
            $is_boolean = $response["is_boolean"];
            $is_int = $response["is_int"];
            $is_float = $response["is_float"];
            $is_string = $response["is_string"];
            $code_name = $response["code_name"];
            ////////////////////////////////////
            if ($is_boolean) {
                $entry_value = $entry_value == '1' || $entry_value == 'yes' || $entry_value == 1 ? true : false;
            } else if ($is_int) {
                $entry_value = intval($entry_value);
            } else if ($is_float) {
                $entry_value = floatval($entry_value);
            } else if ($entry_value == null) {
                $entry_value = '';
            }
            $response["entry_value"] = $entry_value;
            $response["success"] = true;
            return $response;
        } else {
            return array("message" => "Setting doesn't exist", "success" => false);
        }
    }

    public function UpdateSettingByCodeName($companyid, $codename, $entry_value)
    {
        $settings =  $this->getSettingByCodeName($companyid, $codename);
        if ($settings["success"]) {
            $settingid = $settings["id"];
            $dbutils = $this->getCompanyDBUtils($companyid);
            $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE id=:usettingid");
            $stmt->bindparam(":usettingid", $settingid);
            $stmt->execute();
            $counter = $stmt->rowCount();
            if ($counter > 0) {
                $stmt = $dbutils->runQuery("UPDATE pm_settings SET entry_value=:uentryvalue WHERE id=:usettingid");
                $stmt->bindparam(":usettingid", $settingid);
                $stmt->bindparam(":uentryvalue", $entry_value);
                if ($stmt->execute()) {
                    return array("message" => "Setting updated successfully", "success" => true);
                } else {
                    return array("message" => "Something went wrong", "success" => false);
                }
            } else {
                return array("message" => "Setting doesn't exist", "success" => false);
            }
        } else {
            return $settings;
        }
    }

    // You are relating an incident of rooted in crime to an incident 3 centuries of hate and racism.
    public function getSettingByCodeName($companyid, $codename)
    {
        $dbutils = $this->getCompanyDBUtils($companyid);
        $stmt = $dbutils->runQuery("SELECT * FROM pm_settings WHERE code_name=:ucodename");
        $stmt->bindparam(":ucodename", $codename);
        $stmt->execute();
        $counter = $stmt->rowCount();
        ////////////////////////////////
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $entry_value = $response["entry_value"];
            $is_boolean = $response["is_boolean"];
            $is_int = $response["is_int"];
            $is_float = $response["is_float"];
            $is_string = $response["is_string"];
            $code_name = $response["code_name"];
            ////////////////////////////////////
            if ($is_boolean) {
                $entry_value = $entry_value == '1' || $entry_value == 'yes' || $entry_value == 1 ? true : false;
            } else if ($is_int) {
                $entry_value = intval($entry_value);
            } else if ($is_float) {
                $entry_value = floatval($entry_value);
            } else if ($entry_value == null) {
                $entry_value = '';
            }
            $response["entry_value"] = $entry_value;
            $response["success"] = true;
            return $response;
        } else {
            return array("message" => "Setting doesn't exist", "success" => false);
        }
    }
}
