<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/CustomerClass.php") ;
require_once (PATH_MODELS . "activity/CustomerContactClass.php") ;

class CCMApi extends ControllerBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->orgid = $_SESSION[SE_ORGID] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		
		try {
			$this->db->open() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
				case REQ_ADD:
					$this->processSaveCustomer($params) ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function processSaveCustomer($params) {
        $customer_list = json_decode($params['customer_list']);

        // foreach($customer_list as $customer) {
        //     foreach($customer->contact_list as $contact) {
        //         Log::write($contact->prefer_name);
        //     }
        // }
        
        // die();

        $err_count = 0;
        $partial_err = 0;

        $mesg = "";
        foreach($customer_list as $customer) {
            //SAVING DATA
			$result = $this->addCustomer($customer);
			if($result['status']==Status::Error) {
				$mesg .= $result['mesg'];
				$err_count++;
			} else if($result['status']==Status::PartialError) {
				$mesg .= $result['mesg'];
				$err_count++;
				$partial_err = 1;
			} else {
				$mesg .= $result['mesg'];
			}
        }

        //check is there any error during inserting data
        if($err_count > 0) {
            $res_mesg = $mesg;

            if($partial_err == 1) {
                $this->sendJsonResponse(Status::PartialError, $res_mesg, "", $this->type);
            } else {
                $this->sendJsonResponse(Status::Error, $res_mesg, "", $this->type);
            }
        } else {
            //no error
            $this->sendJsonResponse(Status::Ok, "All customer data successfully exported to the system.", "", $this->type);
        }
	}

	private function addCustomer($customer) {
        $clsCustomer  = new CustomerClass($this->db);
        $clsContact   = new CustomerContactClass($this->db);

        $datas        = array();
        $orgid        = $_SESSION[SE_ORGID];
        // $modifyby     = $_SESSION[SE_USERID];
        $modifydate   = date_create('now')->format('Y-m-d H:i:s');
        $ws           = $_SESSION[SE_REMOTE_IP];
        
		$datas[] = $this->db->fieldValue(CustomerTable::C_NAME, $customer->name) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CODE, $customer->code) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_FAX, $customer->fax) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_TELEPHONE, $customer->telephone) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_WEB, $customer->website) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_1, $customer->address);
		$datas[] = $this->db->fieldValue(CustomerTable::C_STATUS, $customer->status);
		$datas[] = $this->db->fieldValue(CustomerTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_WS_ID,$ws) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_BY,$modifyby) ;
		// $datas[] = $this->db->fieldValue(CustomerTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CREATE_DATE,$modifydate) ;

        try {
            $this->db->beginTran();

            $exist = $clsCustomer->getCustomerByCode($customer->code);

            $partial_err = 0;
            if (!is_null($exist)) {
                //update
                $id = $clsCustomer->updateRecord($exist[CustomerTable::C_ID], $datas) ;
				if ($id > 0) {
                    $mesg = "Customer details successfully updated to the system.";

                    //customer contact
                    if (isset($customer->contact_list)) {
                        $result = $this->addCustomerContacts($exist[CustomerTable::C_ID], $customer->contact_list);
                        if ($result != "") {
                            $partial_err = $result['status'] == Status::PartialError ? Status::PartialError : Status::Ok;
                            $mesg .= "\n" . $result['mesg'];
                        }
                    }

					$this->db->commitTran();

                    $ret_data = array();
                    $ret_data['mesg'] = $mesg;
                    $ret_data['status'] = $partial_err == 1 ? Status::PartialError : Status::Ok;

                    return $ret_data;
				} else {
                    $this->db->rollbackTran() ;	

                    $ret_data = array();
                    $ret_data['mesg'] = "Sorry, there is a error in updating customer to the system.";
                    $ret_data['status'] = Status::Error;

                    return $ret_data;
				}
            } else {
                ///new
                $id = $clsCustomer->addRecord($datas);
                if ($id > 0) {
                        $mesg = "Customer details successfully added to the system.";

                        //customer contact
                        if (isset($customer->contact_list)) {
                            $result = $this->addCustomerContacts($id, $customer->contact_list);
                            if ($result != "") {
                                $partial_err = $result['status'] == Status::PartialError ? Status::PartialError : Status::Ok;
                                $mesg .= "\n" . $result['mesg'];
                            }
                        }

                        $content            = array();
                        $content['id']      = $id;

                        $this->db->commitTran();

                        $ret_data = array();
                        $ret_data['mesg'] = $mesg;
                        $ret_data['status'] = $partial_err == Status::PartialError ? Status::PartialError : Status::Ok;

                        return $ret_data;
                    //====================

                    
                } else {
                    $this->db->rollbackTran() ;	

                    $ret_data = array();
                    $ret_data['mesg'] = "Sorry, there is a error in adding new customer to the system.";
                    $ret_data['status'] = Status::Error;

                    return $ret_data;
                }
            }
        } catch (Exception $e) {
            $this->db->rollbackTran() ;	
            Log::write('[Customer]' . $e->getMessage());

            $ret_data = array();
            $ret_data['mesg'] = "Sorry, there is a error in database operation.";
            $ret_data['status'] = Status::Error;

            return $ret_data;
        }
        unset($clsCustomer);
    }

	private function addCustomerContacts($custId, $custContacts) {
        $clsContact = new CustomerContactClass($this->db);
        $mesg = "";

        $orgid      = $_SESSION[SE_ORGID];
        // $modifyby   = $_SESSION[SE_USERID];
        $modifydate = date_create('now')->format('Y-m-d H:i:s');
        $ws         = $_SESSION[SE_REMOTE_IP];

        $partial_err = 0;
        if (!is_null($custContacts) && count($custContacts) > 0) {
            foreach ($custContacts as $contact) {
                $datas = array();
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_ID, $custId);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_NAME, $contact->full_name);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_EMAIL, $contact->email);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_TELEPHONE, $contact->telephone);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_MOBILE, $contact->mobile);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_DESIGNATION, $contact->designation);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_DEPT, $contact->dept);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_REPORT_TO, $contact->report_to);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_ACTIVE, $contact->contact_status); 
                // $datas[] = $this->db->fieldValue(CustomerContactTable::C_MODIFY_BY, $modifyby);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_MODIFY_DATE, $modifydate);

                $rowContact = $clsContact->getCustomerByName($custId, $contact->full_name);
				
                if (!is_null($rowContact) && count($rowContact) > 0) {
                    if ($clsContact->updateRecord($rowContact[CustomerContactTable::C_ID], $datas)) {
                    } else {
                        $partial_err = 1;
                        if ($mesg == "")
                            $mesg = "Failed to insert contact for: ";

                        $mesg .= $contact->full_name . ", ";
                    }
                } else {
                    // $datas[] = $this->db->fieldValue(CustomerContactTable::C_CREATE_BY, $modifyby);
                    $datas[] = $this->db->fieldValue(CustomerContactTable::C_CREATE_DATE, $modifydate);
                    if ($clsContact->addRecord($datas) > 0) {
                    } else {
                        $partial_err = 1;
                        if ($mesg == "")
                            $mesg = "Failed to insert contact for: ";

                        $mesg .= $contact->full_name . ", ";
                    }
                }
            }
        }
        unset($clsContact);

        $ret_data = array();
        $ret_data['mesg'] = $mesg;
        $ret_data['status'] = $partial_err == 1 ? Status::PartialError : Status::Ok;

        return $ret_data;
    }
}

?>