<?php

class Supplier {

    protected $info = array();
    private $year_id;
    private $controller_permission;

    public function __construct() {
        $this->db = DBConnectorFactory::loadDriver();
        $this->year_id = Session::getCurrentYearID();
        $this->controller_permission = Session::getPermissionsObject();

    }

    public function setData(array $data) {
        $this->info = $data;
        return $this;
    }

    public function createSupplier() {
        $this->db->query('START TRANSACTION');
        $date_time = date("Y-m-d H:i:s");
        $account_parent_id = $this->info['account_parent_id'] != '' ? $this->info['account_parent_id'] : null;
        $supplier_group_id = !empty($this->info['supplier_group_id']) ? $this->info['supplier_group_id'] : null;
        $supplier_class_id = !empty($this->info['supp_class_id']) ? $this->info['supp_class_id'] : null;
        $this->info['other_pay_acc_id'] = !empty($this->info['other_pay_acc_id']) ? $this->info['other_pay_acc_id'] : null;
        $this->info['supplier_user_name'] = !empty($this->info['supplier_user_name']) ? $this->info['supplier_user_name'] : '';
        $this->info['supplier_password'] = !empty($this->info['supplier_password']) ? $this->info['supplier_password'] : '';
        $this->info['branch_id'] = !empty($this->info['branch_id']) ? $this->info['branch_id'] : smc_session()['user_accounts']['branch_id'];

        $data = [&$this->info['Supplier_Name'],
            &$this->info['Supplier_Email'],
            &$this->info['Supplier_Phone'],
            &$this->info['Supplier_Company'],
            &$this->info['Supplier_Address'],
            &$this->info['City_ID'],
            &$this->info['Currency_ID'],
            &$this->info['Supplier_PostalCode'],
            &$this->info['Supplier_Country'],
            &$this->info['Supplier_CR'],
            &$this->info['Supplier_Mobile'],
            &$this->info['Supplier_Work_Phone'],
            &$this->info['supplier_due_date_period'],
            &$account_parent_id,
            &$supplier_group_id,
            &$supplier_class_id,
            &smc_session()['user_logged_id'],
            $this->info['supplier_user_name'], $this->info['supplier_password'], $this->info['other_pay_acc_id'],$this->info['supplier_vat'],$this->info['supplier_additional_number']
            ,$this->info['supplier_other_id']
            ,$this->info['branch_id']
        ];

        $this->db->prepare_Stmt('
                                    INSERT 
                                    INTO 
                                        tbl_stock_suppliers 
                                    (
                                        Supplier_Name,
                                        Supplier_Email,
                                        Supplier_Phone,
                                        Supplier_Company,
                                        Supplier_Address,
                                        City_ID,
                                        Currency_ID,
                                        Supplier_PostalCode,
                                        Supplier_Country,
                                        Supplier_CR,
                                        Supplier_Mobile,
                                        Supplier_Work_Phone,
                                        supplier_due_date_period,
                                        account_parent_id,
                                        supplier_group_id,
                                        supplier_class_id,
                                        Logged_ID,user_name,password,other_pay_acc_id,supplier_vat,supplier_additional_number,supplier_other_id , branch_id
                                    ) 
                                        VALUES 
                                    ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', $data);
        $supplier_id = $this->db->id();
        $contacts = json_decode($this->info['contacts'], true);
        if (!empty($contacts))
            self::insertSupplierContacts($contacts, $supplier_id);
        $arr_supp = ['type' => 'supp', 'main_id' => $supplier_id, 'action' => 0, 'date_time' => $date_time,
            'user_id' => smc_session()['user_logged_id']];
        CommonFunctions::add_user_log($arr_supp);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return $error;
    }

    public function deleteSupplier() {
        $supp_id = $this->info['Supplier_ID'];
        $check = self::checkIfSupplierUsed($supp_id);
        if ($check)
            return ['check_supplier'];
        $this->db->query('START TRANSACTION');
        $date_time = date("Y-m-d H:i:s");
        $delete = [&$supp_id];
        $this->db->prepare_Stmt("DELETE FROM tbl_stock_suppliers WHERE  Supplier_ID = ? ", $delete);
        $this->db->prepare_Stmt("DELETE FROM tbl_chart_of_accounts 
                where main_type = 'supp' and main_id = ? ", $delete);
        $arr_supp = ['type' => 'supp', 'main_id' => $supp_id, 'action' => 2, 'date_time' => $date_time,
            'user_id' => smc_session()['user_logged_id']];
        CommonFunctions::add_user_log($arr_supp);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return $error;
    }

    public function updateSupplier() {
        $this->db->query('START TRANSACTION');
        $date_time = date("Y-m-d H:i:s");
        $account_parent_id = $this->info['account_parent_id'] == '' ? null : $this->info['account_parent_id'];
        $supplier_group_id = !empty($this->info['supplier_group_id']) ? $this->info['supplier_group_id'] : null;
        $supplier_class_id = !empty($this->info['supp_class_id']) ? $this->info['supp_class_id'] : null;
        $this->info['other_pay_acc_id'] = !empty($this->info['other_pay_acc_id']) ? $this->info['other_pay_acc_id'] : null;
        $this->info['supplier_user_name'] = !empty($this->info['supplier_user_name']) ? $this->info['supplier_user_name'] : '';
//        $this->info['supplier_password'] = !empty($this->info['supplier_password']) ? $this->info['supplier_password'] : '';

        $data = [&$this->info['Supplier_Name'],
            &$this->info['Supplier_Email'],
            &$this->info['Supplier_Phone'],
            &$this->info['Supplier_Mobile'],
            &$this->info['Supplier_Work_Phone'],
            &$this->info['Supplier_Company'],
            &$this->info['Supplier_Address'],
            &$this->info['City_ID'],
            &$this->info['Currency_ID'],
            &$this->info['Supplier_PostalCode'],
            &$this->info['Supplier_Country'],
            &$this->info['Supplier_CR'],
            &$this->info['supplier_due_date_period'],
            &$account_parent_id,
            &$supplier_group_id,
            &$supplier_class_id,
            $this->info['supplier_user_name'],
            $this->info['other_pay_acc_id'],
            $this->info['supplier_vat'],
            $this->info['supplier_additional_number'],
            $this->info['supplier_other_id'],
            $this->info['branch_id'],

            &$this->info['Supplier_ID']
        ];
        $this->db->prepare_Stmt('
                                    UPDATE 
                                        tbl_stock_suppliers
                                    SET 
                                        Supplier_Name       = ?,
                                        Supplier_Email      = ?,
                                        Supplier_Phone      = ?,
                                        Supplier_Mobile     = ?,
                                        Supplier_Work_Phone  = ?,
                                        Supplier_Company    = ?,
                                        Supplier_Address    = ?,
                                        City_ID             = ?,
                                        Currency_ID         = ?,
                                        Supplier_PostalCode = ?,
                                        Supplier_Country    = ?,
                                        Supplier_CR                      = ?,
                                        supplier_due_date_period         = ?,
                                        account_parent_id         = ?,
                                        supplier_group_id         = ?,
                                        supplier_class_id         = ?,
                                        user_name=?,other_pay_acc_id=?,supplier_vat=?,supplier_additional_number=?,supplier_other_id=?,
                                        branch_id = ?
                                    WHERE 
                                        Supplier_ID         = ?', $data);
        $this->db->prepare_Stmt('delete from tbl_customer_supplier_contacts where main_id=? and type_id = 2', [&$this->info['Supplier_ID']]);
        $contacts = json_decode($this->info['contacts'], true);
        if (!empty($contacts))
            self::insertSupplierContacts($contacts, $this->info['Supplier_ID']);
        $arr_supp = ['type' => 'supp', 'main_id' => $this->info['Supplier_ID'], 'action' => 1, 'date_time' => $date_time,
            'user_id' => smc_session()['user_logged_id']];
        CommonFunctions::add_user_log($arr_supp);
        $error = $this->db->error();
        if (empty($error)) {
            $this->db->query('COMMIT');
        } else {
            $this->db->query('ROLLBACK');
        }
        return $error;
    }

    public function insertSupplierContacts($contacts, $supplier_id) {
        foreach ($contacts as $contact) {
            $this->db->prepare_Stmt('insert into tbl_customer_supplier_contacts 
            (contact_name,contact_position,contact_phone_number,contact_note,main_id,type_id) VALUES (?,?,?,?,?,2)', [&$contact['contact_name'], &$contact['contact_position'],
                &$contact['contact_phone_number'], &$contact['contact_note'], &$supplier_id]);
        }
    }

    public function ViewAllDetails($supplier_id) {
        $data = array();
        $query = $this->db->query('SELECT s.*,c.*,ct.*,ca.Account_Code,ca.Account_ID,ca.Account_Name,cu.*,
            s.account_parent_id,coa.Account_Name as account_parent_name,general_group.group_name,
            general_class.class_name as supp_class_name,s.Supplier_CR as CR,
            ifnull(concat(pac.Account_Name,"-",pac.Account_Code),"") as other_pay_acc_name
            FROM tbl_stock_suppliers s 
            LEFT JOIN tbl_all_cities ct ON s.City_ID = ct.ID
            LEFT JOIN tbl_all_countries c ON s.Supplier_Country = c.Country_ID
            join tbl_chart_of_accounts ca on (ca.main_id = s.Supplier_ID 
                 and ca.main_type = "supp" and ca.sub_type = "main")
            left join tbl_chart_of_accounts coa on coa.Account_ID = s.account_parent_id
            left join tbl_common_currency cu on cu.Currency_ID = s.Currency_ID
            left join tbl_general_groups general_group on general_group.group_id = s.supplier_group_id
            left join tbl_general_classes general_class on general_class.class_id = s.supplier_class_id
            left join tbl_chart_of_accounts pac on pac.Account_ID = s.other_pay_acc_id
            WHERE s.Supplier_ID = "' . $supplier_id . '" ');

        while ($row = $this->db->assoc($query)) {
            $row['branch_name'] = CommonBusiness::getBranchByBranchId($row['branch_id'])['branch_name'];
            $data[] = $row;
        }
        return $data;
    }

    //    public function view($sup_id = null) {
    //        $condition = '';
    //        $data = array();
    //        if ($sup_id != null)
    //            $condition .= 'where s.Supplier_ID = "' . $sup_id . '"';
    //        $query = $this->db->query('SELECT 
    //                                            s.*,
    //                                            cy.*,
    //                                            a.Account_Code
    //                                        FROM
    //                                            tbl_stock_suppliers s  
    //                                        join tbl_chart_of_accounts a on a.main_id = s.Supplier_ID
    //                                        and a.main_type = "supp" and a.sub_type = "main"
    //                                        
    //                                        LEFT JOIN 
    //                                            tbl_all_countries cy
    //                                        ON 
    //                                            s.Supplier_Country = cy.Country_ID
    //                                        
    //                                            ' . $condition);
    //        while ($row = $this->db->assoc($query)) {
    //            $row['Default_Currency'] = CurrencyFactory::getDefaultCurrencySymbol();
    //            $row['Supplier_Balance'] = self::returnBalanceByAccount($row['Supplier_ID']);
    //            $row[] = self::viewSupplierSumPurchases($row['Supplier_ID']);
    //            $data[] = $row;
    //        }
    //
    //
    //        return $data;
    //    }

    public function returnBalanceByAccount($supplier_id) {
        $balance = 0.0;
        $cond = '';
        if (smc_session()['default_setting']['show_related_acc'] == 1) {
            $cond.=' and sub_type in ("main","fa","exp") ';
        } else {
            $cond.=' and c.sub_type = "main" ';
        }
        $query = $this->db->query('SELECT 
                                        t.Currency_ID,
                                        t.Transaction_Amount,
                                        t.Transaction_Type,
                                        t.Current_Ex_Rate as rate
                                    FROM 
                                        tbl_accounting_transactions t
                                     JOIN 
                                        tbl_chart_of_accounts c
                                    ON 
                                        c.Account_ID = t.Account_ID
                                    WHERE  
                                        c.main_type = "supp" ' . $cond . '
                                    AND 
                                        c.main_id = "' . $supplier_id . '" and t.current_year_id = "' . $this->year_id . '"
                ');
        while ($row = $this->db->assoc($query)) {
            $amount = $row['rate'] == 0 ? CurrencyFactory::returnLocalCurrencyValue($row['Currency_ID'], $row['Transaction_Amount']) : ($row['rate'] * $row['Transaction_Amount']);
            if ($row['Transaction_Type'] == 'Credit')
                $amount*= (-1);
            $balance += $amount;
            //            if ($row['Transaction_Type'] == 'Credit')
            //                $balance += CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Transaction_Amount']);
            //            else
            //                $balance -= CurrencyFactory::returnPriceInDefaultCurrencyValue($row['Currency_ID'], $row['Transaction_Amount']);
        }
        return $balance;
    }

    public function viewSupplierSumPurchases($sup_id) {
        $sum_purchases = 0;
        $query = $this->db->query('SELECT sum(p.Purchase_Net_Total*current_rate) as total
            FROM tbl_inventory_purchases p WHERE p.Supplier_ID = "' . $sup_id . '"');
        $row = $this->db->assoc($query);
        if (!empty($row))
            $sum_purchases = $row['total'];
        return $sum_purchases;
    }

    public function viewSupplierInv($supp_id) {
        $data = array();
        $query = $this->db->query('SELECT 
                                            s.Supplier_Name,
                                            p.*

                                        FROM 
                                            tbl_stock_suppliers s 
                                        LEFT JOIN 
                                            tbl_inventory_purchases p
                                        ON 
                                            s.Supplier_ID = p.Supplier_ID

                                        WHERE 
                                            s.Supplier_ID = "' . $supp_id . '"
                                        AND 
                                            s.Status_ID = 1');
        while ($row = $this->db->assoc($query)) {


            $data[] = $row;
        }

        return $data;
    }

    public function viewSuppliersForAutoComplete($sup_id = null, $condition = "") {

        $data = array();
        if ($sup_id != null)
            $condition .= ' and s.Supplier_ID = "' . $sup_id . '"';
        if (!empty($this->info['Status_ID'])) {
            $condition .= ' and s.Status_ID = "1" ';
        }
        if (isset($this->info['is_edited'])) {
            $condition .= ' and (s.Status_ID = 1 or (s.Status_ID = 0 and s.Supplier_ID = "' . $this->info['is_edited'] . '") )';
        }
        $query = $this->db->query('SELECT 
                                            s.*,
                                            cy.*,
                                            ac.ID,
                                            ac.Name,
                                            a.Account_Code,
                                            a.Account_ID

                                        FROM
                                            tbl_stock_suppliers s  
                                        join tbl_chart_of_accounts a on a.main_id = s.Supplier_ID
                                        and a.main_type = "supp" and a.sub_type = "main"
                                        LEFT JOIN 
                                                tbl_all_countries cy
                                        ON 
                                                s.Supplier_Country = cy.Country_ID
                                        LEFT JOIN
                                            tbl_all_cities  ac
                                        ON
                                            s.City_ID = ac.ID
                                            where 1=1 
                                        ' . $condition . '
                                        GROUP BY 
                                            s.Supplier_ID');
        while ($row = $this->db->assoc($query)) {
            $row['Default_Currency'] = CurrencyFactory::getDefaultCurrencySymbol();
            $row['Supplier_Balance'] = self::returnBalanceByAccount($row['Supplier_ID']);
            $row[] = self::viewSupplierSumPurchases($row['Supplier_ID']);
            $data[] = $row;
        }

        //        for ($i = 0; $i < count($data); $i++) {
        //
        //            $total = self::viewSupplierSumPurchases($data[$i]['Supplier_ID']);
        //            array_push($data[$i], $total);
        //        }
        return $data;
    }

    public static function ViewAllDetailsCustomerVendor($acc_code) {
        $data = array();
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('SELECT main_type,main_id 
            FROM tbl_chart_of_accounts WHERE Account_ID="' . $acc_code . '"');
        $query1 = $db->assoc($query);

        if ($query1['main_type'] == 'cust') {

            $cusomter = $db->query('SELECT
                                                        cu.Customer_Name AS Name,
                                                        cu.Customer_Email AS Email,
                                                        cu.Customer_Phone AS Phone,
                                                        cu.Customer_Mobile AS Address,
                                                        cu.customer_vat AS customer_vat,
														cu.Customer_CR AS reg_nb,
                                                        c.Name AS City,
                                                        co.Country_Name
                                                    FROM 
                                                        tbl_customers   cu
                                                    LEFT JOIN
                                                        tbl_all_cities c
                                                    ON 
                                                        c.ID = cu.Customer_City_ID
                                                    LEFT JOIN
                                                        tbl_all_countries  co
                                                    ON 
                                                        co.Country_ID = cu.Customer_Country_ID
                                                    WHERE 
                                                        Customer_ID = "' . $query1['main_id'] . '"');
        } else {
            $cusomter = $db->query('SELECT
                                                            s.Supplier_Name AS Name,
                                                            s.Supplier_Email AS Email,
                                                            s.Supplier_Mobile AS Phone ,
                                                            s.Supplier_Address AS Address,
                                                            s.supplier_vat AS supplier_vat,
															s.Supplier_CR AS reg_nb,
                                                            c.Name AS City,
                                                            co.Country_Name

                                                        FROM 
                                                            tbl_stock_suppliers  s
                                                        LEFT JOIN
                                                            tbl_all_cities c
                                                        ON 
                                                            c.ID = s.City_ID
                                                        LEFT JOIN
                                                            tbl_all_countries  co
                                                        ON 
                                                            co.Country_ID = s.Supplier_Country
                                                        WHERE 
                                                            Supplier_ID = "' . $query1['main_id'] . '"');
        }
        $row = $db->assoc($cusomter);

        $data[] = $row;

        return $data;
    }

    /**
     * Generic function to get an uploaded $_FILE[name_of_file] and save it to a specific path 
     * @param [[Type]] $FileName The name of the input[file] tag that is assigned in the client-side
     * @param [[Type]] $SavePath Destination path
     */
    public function SaveUploadedPhoto($FileName, $SavePath) {

        if (!isset($_FILES[$FileName]))
            return false;
        $SaveToPath = substr($SavePath, 0, strrpos($SavePath, "/") + 1);
        $SaveAsFile = substr($SavePath, strrpos($SavePath, "/") + 1);
        $SaveAsExtention = explode(".", $SaveAsFile);
        $SaveAsExtention = strtolower($SaveAsExtention[count($SaveAsExtention) - 1]);
        $SaveAsFile = substr($SaveAsFile, 0, strrpos($SaveAsFile, "."));
        $fileType = explode(".", basename($_FILES[$FileName]['name']));
        $fileType = strtolower($fileType[count($fileType) - 1]);
        $DestinationFile = $SaveToPath . $SaveAsFile . ".";
        if (file_exists($DestinationFile . $fileType))
            unlink($DestinationFile . $fileType);

        move_uploaded_file($_FILES[$FileName]['tmp_name'], $DestinationFile . $fileType);

        if ($fileType == "png" && $SaveAsExtention == "jpg") {
            if (file_exists($DestinationFile . $fileType))
                unlink($DestinationFile . "jpg");
            $image = imagecreatefrompng($DestinationFile . $fileType);
            imagejpeg($image, $DestinationFile . $SaveAsExtention, 100);
            imagedestroy($image);
            if (file_exists($DestinationFile . $fileType))
                unlink($DestinationFile . $fileType);
        }
    }

    public function supplierSearch($term = null, $page, $limit) {
        $data = array();
        $data['is_more'] = false;
        $data['data'] = array();
        $cond = '';
        $data_filter = array();

        if (!is_null($term)) {
            $cond .=' where Supplier_Name LIKE ?';
            $data_filter[] = "%" . $term . "%";
        }
        if (!empty($this->info['Status_ID'])) {
            $cond .= ' and Status_ID = "1" ';
        }
        if (!empty($this->info['group'])) {
            $cond .= ' and supplier_group_id = "' . $this->info['group'] . '" ';
        }
        if (isset($this->info['is_edited'])) {
            $cond .= ' and (Status_ID = 1 or (Status_ID = 0 and Supplier_ID = ? ) )';
            $data_filter[] = $this->info['is_edited'];
        }
        if($this->controller_permission->hasPermission('Branches')){
            $cond  .= '';
        }else{
            $cond  .= ' and (branch_id ="' . (smc_session()['user_accounts']['branch_id']) . '" or Supplier_ID = 0   )  '  ;
        }

        $query = $this->db->prepare_Stmt('select  
                                    Supplier_ID as id,
                                    Supplier_Name as text
                                from 
                                    tbl_stock_suppliers
                                ' . $cond . '
                                limit ' . ($page * $limit) . ',' . ($limit + 1), $data_filter);
        while ($row = $this->db->assoc($query)) {
            $data['data'][] = $row;
        }
        if (count($data['data']) > $limit) {
            array_pop($data['data']);
            $data['is_more'] = true;
        }
        return $data;
    }

    public static function getSupplierByID($id, $with_balance = 0, $is_actual = 0) {
        $db = DBConnectorFactory::loadDriver();
        $query_supp = $db->query('SELECT 
                                        s.Supplier_Name AS Name,
                                        s.supplier_vat AS person_vat,
                                        s.Supplier_CR AS person_cr,
                                        s.Supplier_Email AS Email,
                                        s.Supplier_Phone AS Phone,
                                        s.Supplier_Mobile AS Mobile,
                                        s.Supplier_Company AS Company,
                                        s.Supplier_Address AS Address,
                                        c.Country_Name,
                                        ca.Account_Code,
                                        ca.Account_ID,s.other_pay_acc_id,
                                        s.supplier_due_date_period as due_date_period 
                                        FROM 
                                            tbl_stock_suppliers s 
                                        LEFT JOIN
                                                tbl_all_countries c
                                        ON 
                                                s.Supplier_Country = c.Country_ID
                                       join tbl_chart_of_accounts ca on ca.main_id = s.Supplier_ID
                                        AND 
                                            ca.main_type = "supp" and ca.sub_type = "main"

                                        WHERE 
                                            s.Supplier_ID = "' . $id . '"');
        $data = $db->assoc($query_supp);
        if ($with_balance <> 0) {
            $today = Date::getToday();
            $report = new Report;
            $data['Customer_Balance'] = $report->returnSupplierExactBalance($id, smc_session()["local_currency"], smc_session()['start_date'], $today, 0, $is_actual)['Balance'];
        }
        return $data;
    }
    public static function get_multi_SupplierByID($id, $with_balance = 0, $is_actual = 0,$DB) {
        $db = DBConnectorFactory::loadDriver();
        $query_supp = $db->query('SELECT 
                                        s.Supplier_Name AS Name,
                                        s.Supplier_Email AS Email,
                                        s.Supplier_Phone AS Phone,
                                        s.Supplier_Mobile AS Mobile,
                                        s.Supplier_Company AS Company,
                                        s.Supplier_Address AS Address,
                                        c.Country_Name,
                                        ca.Account_Code,
                                        ca.Account_ID,s.other_pay_acc_id,
                                        s.supplier_due_date_period as due_date_period 
                                        FROM 
                                            '.$DB.'.tbl_stock_suppliers s 
                                        LEFT JOIN
                                        '.$DB.'.tbl_all_countries c
                                        ON 
                                                s.Supplier_Country = c.Country_ID
                                       join '.$DB.'.tbl_chart_of_accounts ca on ca.main_id = s.Supplier_ID
                                        AND 
                                            ca.main_type = "supp" and ca.sub_type = "main"

                                        WHERE 
                                            s.Supplier_ID = "' . $id . '"');
        $data = $db->assoc($query_supp);
        if ($with_balance <> 0) {
            $today = Date::getToday();
            $report = new Report;
            $data['Customer_Balance'] = $report->returnSupplierExactBalance($id, smc_session()["local_currency"], smc_session()['start_date'], $today, 0, $is_actual)['Balance'];
        }
        return $data;
    }

    public function checkIfSupplierUsed($cid) {
        $query_account = $this->db->query('select Account_ID,Account_Code 
                from tbl_chart_of_accounts a
                where main_type = "supp" and main_id = "' . $cid . '"');
        $s_account_arr = array();
        while ($row = $this->db->assoc($query_account)) {
            $s_account_arr[] = $row['Account_ID'];
        }

        //check  if supplier is used in transactions
        $trans_query = $this->db->query('select * from tbl_accounting_transactions 
            where Account_ID in(' . implode(',', $s_account_arr) . ') limit 1');
        $trans_count = $this->db->rowsno($trans_query);
        if ($trans_count > 0) {
            return true;
        }
        //check  if supplier is used in purchases
        $pur_query = $this->db->query('select * from tbl_inventory_purchases where Supplier_ID = "' . $cid . '" limit 1');
        $pur_count = $this->db->rowsno($pur_query);
        if ($pur_count > 0) {
            return true;
        }

        //check  if supplier is used in return
        $return_query = $this->db->query('select * from tbl_accounting_return_invoices where Person_ID = "' . $cid . '" and Is_Customer_Invoice = 0 limit 1');
        $return_count = $this->db->rowsno($return_query);
        if ($return_count > 0) {
            return true;
        }

        //check if  supplier is used in purchase order
        $porder_query = $this->db->query('select * from tbl_purchase_order where Supplier_ID = "' . $cid . '" and is_sales = 0 limit 1');
        $porder_count = $this->db->rowsno($porder_query);
        if ($porder_count > 0) {
            return true;
        }
        //check if  supplier is used in expenses
        $expense_query = $this->db->query('select * from tbl_accounting_expenses where Supplier_ID = "' . $cid . '" limit 1');
        $expense_count = $this->db->rowsno($expense_query);
        if ($expense_count > 0) {
            return true;
        }
        //check if  supplier is used in prepaids
        $prepaid_query = $this->db->query('select * from tbl_accounting_prepaid_expense_income where Supplier_ID = "' . $cid . '" limit 1');
        $prepaid_count = $this->db->rowsno($prepaid_query);
        if ($prepaid_count > 0) {
            return true;
        }
        //check if  supplier is used in product
        $product_query = $this->db->query('select * from tbl_stock_products where main_supplier_id = "' . $cid . '" limit 1');
        $product_count = $this->db->rowsno($product_query);
        if ($product_count > 0) {
            return true;
        }

        return false;
    }

    public static function returnSuppVATAccount($supp_id) {
        $db = DBConnectorFactory::loadDriver();

        $query = $db->query('SELECT Account_ID,Account_Code FROM tbl_chart_of_accounts
                            WHERE main_id = "' . $supp_id . '" and main_type="supp"
                            AND sub_type="pur_vat"');
        $row = $db->assoc($query);
        return $row;
    }

    public static function getSupplierAccount($supplier_id) {
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('select 
                                Account_ID 
                                from tbl_chart_of_accounts 
                                where main_id = "' . $supplier_id . '"
                                    and main_type="supp" and sub_type="main"
                                ');
        $row = $db->assoc($query)['Account_ID'];
        return $row;
    }

    public static function getSupplierMainAcc() {
        $data = array();
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('select concat(s.main_type,"#",s.sub_type) as acc_setting,concat(Account_Code," - ",Account_Name) as Account_Name from tbl_account_setting s
            join tbl_chart_of_accounts a on a.Account_ID = s.acc_setting_value
                where s.main_type = "supp" and s.sub_type in("main","fa","exp")');
        while ($row = $db->assoc($query)) {
            $data[] = $row;
        }
        return $data;
    }

    public static function get_all_aupp_accs($id) {
        $data = array();
        $db = DBConnectorFactory::loadDriver();
        $sup_query = $db->query('SELECT  Account_ID,sub_type   FROM tbl_chart_of_accounts 
            WHERE main_id = "' . $id . '" and main_type="supp" ');
        while ($row = $db->assoc($sup_query)) {
            $data[$row['sub_type']] = $row['Account_ID'];
        }
        return $data;
    }

    public static function get_cash_supplier_acc() {
        $data = array();
        $db = DBConnectorFactory::loadDriver();
        $query = $db->query('select Account_ID,Account_Code,Account_Name
            from tbl_chart_of_accounts where main_type="supp" and sub_type="main" and main_id=0');
        $row = $db->assoc($query);
        if (!empty($row))
            $data = $row;
        return $data;
    }

    public function check_supplier_classes($supp_id) {
        $data = array();
        $query = $this->db->query('select Class_ID,Class_Name from tbl_pricing_class 
            where supplier_id = "' . $supp_id . '"');
        $rowsno = $this->db->rowsno($query);
        if ($rowsno == 1)
            $data[] = $this->db->assoc($query);
        return $data;
    }
    public function check_supplier_phone($Supplier_Mobile) {
        $query = $this->db->query('SELECT * FROM `tbl_stock_suppliers` WHERE Supplier_Mobile = "' . $Supplier_Mobile . '" ');
        $row = $this->db->assoc($query);
        return $row;
    }


}
