<?php
require_once("class.utils.php");
class Company
{
    ////
    private $restapi;
    /////
    public $utils;
    /////
    public function __construct($restapi = null)
    {
        $this->restapi = $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));
        }
    }

    public function CompanyNameExists($companyname)
    {
        $stmt = $this->restapi->dbutils->runQuery("SELECT * FROM pm_company WHERE company_name=:ucompanyname");
        $stmt->bindparam(":ucompanyname", $companyname);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            return true;
        } else {
            return false;
        }
    }


    public function CompanyExistsById($companyid)
    {
        $stmt = $this->restapi->dbutils->runQuery("SELECT * FROM pm_company WHERE id=:ucompanyid");
        $stmt->bindparam(":ucompanyid", $companyid);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function getAllCompanies()
    {
        $results = [];
        $stmt = $this->restapi->dbutils->runQuery("SELECT * FROM api_company WHERE user_id=:uuserid");
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($results, $response);
        }
        return $results;
    }

    public function getCompany($companyid)
    {
        $response = array();
        $stmt = $this->restapi->dbutils->runQuery("SELECT * FROM pm_company WHERE id=:ucompanyid OR company_no=:ucompanyid");
        $stmt->bindparam(":ucompanyid", $companyid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
        } else {
            return array("message" => "Company doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }

    public function createCompany($fields)
    {
        $logo = $this->restapi->utils->getDefaultLogo();
        $favicon = $this->restapi->utils->getDefaultFavIcon();
        // print_r($fields);
        extract($fields);
        if ($this->CompanyNameExists($company_name)) {
            die($this->restapi->Response(["message" => "Company name already taken", "success" => false], 400));
        } else {
            $companyno = $this->utils->getRandom();
            /// run and insert query
            $stmt3 = $this->restapi->dbutils->runQuery("
                        INSERT INTO pm_company SET
                        company_name = :ucompanyname,
                        company_no = :ucompanyno,
                        site_title = :usitetitle,
                        db_name = :udbname,
                        logo = :ulogo,
                        favicon = :ufavicon,
                        email = :uemail,
                        address = :uaddress,
                        postcode = :upostcode,
                        city = :ucity,
                        mobile = :umobile,
                        phone = :uphone,
                        is_active = :uisactive,
                        last_updated = NOW()");
            $stmt3->bindParam(":ucompanyname", $company_name);
            $stmt3->bindParam(":ucompanyno", $companyno);
            $stmt3->bindParam(":usitetitle", $site_title);
            $stmt3->bindParam(":udbname", $db_name);
            $stmt3->bindParam(":ulogo", $logo);
            $stmt3->bindParam(":ufavicon", $favicon);
            $stmt3->bindParam(":uemail", $email);
            $stmt3->bindParam(":uaddress", $address);
            $stmt3->bindParam(":upostcode", $postcode);
            $stmt3->bindParam(":ucity", $city);
            $stmt3->bindParam(":umobile", $mobile);
            $stmt3->bindParam(":uphone", $phone);
            $stmt3->bindParam(":uisactive", $is_active);
            if ($stmt3->execute()) {
                $last_inserted_id = $this->restapi->dbutils->conn->lastInsertId();
                return $this->getCompany($last_inserted_id);
            } else {
                die($this->restapi->Response(["message" => "Something went wrong, please try again laiter", "success" => false], 400));
            }
        }
    }


    public function updateCompany($fields, $companyid)
    {
        extract($fields);
        $old_company = $this->getCompany($companyid);
        if ($old_company["success"]) {
            $company_name = !isset($fields["company_name"]) || empty($fields["company_name"]) ? $old_company["company_name"] : $company_name;
            $site_title = !isset($fields["site_title"]) || empty($fields["site_title"]) ? $old_company["site_title"] : $site_title;
            $logo = !isset($fields["logo"]) || empty($fields["logo"]) ? $old_company["logo"] : $logo;
            $favicon = !isset($fields["favicon"]) || empty($fields["favicon"]) ? $old_company["favicon"] : $favicon;
            $email = !isset($fields["email"]) || empty($fields["email"]) ? $old_company["email"] : $email;
            $address = !isset($fields["address"]) || empty($fields["address"]) ? $old_company["address"] : $address;
            $postcode = !isset($fields["postcode"]) || empty($fields["postcode"]) ? $old_company["postcode"] : $postcode;
            $city = !isset($fields["city"]) || empty($fields["city"]) ? $old_company["city"] : $city;
            $mobile = !isset($fields["mobile"]) || empty($fields["mobile"]) ? $old_company["mobile"] : $mobile;
            $phone = !isset($fields["phone"]) || empty($fields["phone"]) ? $old_company["phone"] : $phone;
            /// run and insert query
            $stmt3 = $this->restapi->dbutils->runQuery("
                        UPDATE pm_company SET
                        company_name = :ucompanyname,
                        site_title = :usitetitle,
                        logo = :ulogo,
                        favicon = :ufavicon,
                        email = :uemail,
                        address = :uaddress,
                        postcode = :upostcode,
                        city = :ucity,
                        mobile = :umobile,
                        phone = :uphone,
                        last_updated = NOW() WHERE id=:ucompanyid OR company_no=:ucompanyid");
            $stmt3->bindParam(":ucompanyname", $company_name);
            $stmt3->bindParam(":usitetitle", $site_title);
            $stmt3->bindParam(":ulogo", $logo);
            $stmt3->bindParam(":ufavicon", $favicon);
            $stmt3->bindParam(":uemail", $email);
            $stmt3->bindParam(":uaddress", $address);
            $stmt3->bindParam(":upostcode", $postcode);
            $stmt3->bindParam(":ucity", $city);
            $stmt3->bindParam(":umobile", $mobile);
            $stmt3->bindParam(":uphone", $phone);
            $stmt3->bindParam(":ucompanyid", $companyid);
            if ($stmt3->execute()) {
                $last_inserted_id = $this->restapi->dbutils->conn->lastInsertId();
                return $this->getCompany($last_inserted_id);
            } else {
                die($this->restapi->Response(["message" => "Something went wrong, please try again laiter", "success" => false], 400));
            }
        }
    }

    public function getCompanyByUserId($userid)
    {
        $response = array();
        $stmt1 = $this->restapi->dbutils->runQuery("SELECT * FROM pm_user WHERE id=:uuserid");
        $stmt1->bindparam(":uuserid", $userid);
        $stmt1->execute();
        $counter = $stmt1->rowCount();
        //////////////////////////////////////////////////////
        if ($this->restapi->dbutils->rowCount() == 0) {
            die($this->restapi->Response(["message" => "User doesn't exist", "success" => false], 400));
        }
        ///////////////////////////////////////////////////
        $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
        $companyid = $row1["company"];
        //////////////////////////////////////
        $stmt = $this->restapi->dbutils->runQuery("SELECT * FROM pm_company WHERE id=ucompanyid");
        $stmt->bindparam(":ucompanyid", $companyid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter == 1) {
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $row["success"] = false;
            return $row;
        } else {
            die($this->restapi->Response(["message" => "Company doesn't exist", "success" => false], 400));
        }
        return $response;
    }
}
