<?php

define('CMS__APP_VERSION', 1.0);
header('Content-Type: application/json');

class app extends app_base_class {

    /**
     * Internal Functions
     * ====================================================================>
     */
    private function current_page() {
        $current_page = 1;
        if (isset($this->_body['page']) && is_numeric($this->_body['page']) && $this->_body['page'] > 0 /* && $this->_body['page'] <= $last_page */)
            $current_page = $this->_body['page'];
        return ($current_page - 1);   //we return -1 since we need it for the query limit offset
    }

    //
    private function build_records($records_per_page, $query, $param_arr = array(), $callback_ft = null) {
        $offset_items = $records_per_page * $this->current_page();
        $stmt = $this->db->query_execute($query . " limit {$offset_items}, " . ($records_per_page + 1), $param_arr);
        $crnt_row_no = 0;
        $is_more = 0;
        if (empty($callback_ft))
            $callback_ft = function($row) {
                return $row;
            };
        $arr = array();
        while ($row = $this->db->query_fetch($stmt)) {
            $crnt_row_no++;
            if ($crnt_row_no > $records_per_page) {
                $is_more = 1;
                break;
            }
            $arr[] = $callback_ft($row);
        }
        return array('data' => $arr, 'is_more' => $is_more);
    }

    /**
     * Functions for send data to App. from server
     * ====================================================================>
     */
    public function get_crm_customers() {
        $cond = '';
        $param_arr = array();
        if (!empty($this->_body['organization_customer_name'])) {
            $cond .= " and organization_customer_name like ? ";
            $param_arr[] = "%{$this->_body['organization_customer_name']}%";
        }
        $rtrn_arr = $this->build_records(20, "SELECT * FROM `all_organizations` where 1=1 {$cond} ", $param_arr);
        //
        die(json_encode($rtrn_arr));
    }

    //
    public function get_crm_calendar_activities() {
        $cond = '';
        $param_arr = array();
        if (!empty($this->_body['organization_customer_name'])) {
            $cond .= " and organization_customer_name like ? ";
            $param_arr[] = "%{$this->_body['organization_customer_name']}%";
        }
        if (!empty($this->_body['organization_id'])) {
            $cond .= " and organization_id = ? ";
            $param_arr[] = $this->_body['organization_id'];
        }
        if (!empty($this->_body['from_date'])) {
            $cond .= " and date(`start`) >= ? ";
            $param_arr[] = $this->_body['from_date'];
        }
        if (!empty($this->_body['to_date'])) {
            $cond .= " and date(`end`) >= ? ";
            $param_arr[] = $this->_body['to_date'];
        }
        if (!empty($this->_body['activity_type_id'])) {
            $cond .= " and activity_type_id = ? ";
            $param_arr[] = $this->_body['activity_type_id'];
        }
        $rtrn_arr = array();
        $stmt = $this->db->query_execute("SELECT *, date(start) as start_date FROM `all_activities` where 1=1 {$cond} limit 100", $param_arr);
        while ($row = $this->db->query_fetch($stmt))
            $rtrn_arr/* [$row['start_date']] */[] = $row;
        //
        die(json_encode(array('data' => $rtrn_arr)));
    }

    //
    public function get_crm_customer_meetings() {
        $cond = '';
        $param_arr = array();
        //
        $cond .= " and activity_type_id = ? ";
        $param_arr[] = 2;   //id 2 for meeting
        if (!empty($this->_body['organization_id'])) {
            $cond .= " and organization_id = ? ";
            $param_arr[] = $this->_body['organization_id'];
        }
        if (!empty($this->_body['from_date'])) {
            $cond .= " and date(`start`) >= ? ";
            $param_arr[] = $this->_body['from_date'];
        }
        if (!empty($this->_body['to_date'])) {
            $cond .= " and date(`end`) >= ? ";
            $param_arr[] = $this->_body['to_date'];
        }
        //
		
        $rtrn_arr = $this->build_records(20, "SELECT * FROM `all_activities` where 1=1 {$cond} ", $param_arr);
        die(json_encode($rtrn_arr));
    }

    //
    public function get_crm_customer_notes() {
        $cond = '';
        $param_arr = array();
        if (!empty($this->_body['organization_id'])) {
            $cond .= " and organization_id = ? ";
            $param_arr[] = $this->_body['organization_id'];
        }
		
        $rtrn_arr = $this->build_records(20, "SELECT * FROM `all_notes` where 1=1 {$cond} 
            order by note_date desc, note_id desc ", $param_arr);
        //
        die(json_encode($rtrn_arr));
    }

    /**
     * Functions for get data from App. to server
     * =========================================================================>
     */
    public function insert_customer_note() {
        if (empty($this->_body['organization_id']) || empty($this->_body['note_content']))
            $this->die_error('send note and customer id!');
        $param_arr = array($this->_body['note_content'], $this->_body['organization_id'], date('Y-m-d H:i:s'));
        $stmt = $this->db->query_execute('insert into tbl_deals_notes (`note_content`,  `organization_id`, `note_date`) VALUES (?,?,?) ', $param_arr);
        die(json_encode(array('msg' => 'note added successfully.')));
    }

    //
    public function start_customer_visit() {
        if (empty($this->_body['organization_id']) || !isset($this->_body['user_longitude']) || !isset($this->_body['user_lattitude']))
            $this->die_error('send location and customer id!');
        $current_date = date('Y-m-d H:i:s');
        $user_id = $this->get_login_user_id();
        $param_arr = array('Meeting', 2, $this->_body['organization_id'], $current_date, 1
            , $this->_body['user_lattitude'], $this->_body['user_longitude'], $current_date, $current_date, $user_id, $current_date, $user_id, $current_date);
        $stmt = $this->db->query_execute('INSERT INTO `tbl_deals_activity`( `activity_title`, `activity_type_id`, `organization_id`,  `start_date`, `activity_checked`
            ,activity_start_lat, activity_start_lng, `activity_created_at`, `activity_checked_at`, `created_by`, `date_created`,modified_by,last_modified) 
		VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ', $param_arr);
        $meeting_id = $this->db->last_id();
        die(json_encode(array('msg' => 'meeting started successfully.', 'id' => "{$meeting_id}")));
    }

    //
    public function end_customer_visit() {
        if (empty($this->_body['activity_id']) || !isset($this->_body['user_longitude']) || !isset($this->_body['user_lattitude']))
            $this->die_error('send location and activity id!');
        $current_date = date('Y-m-d H:i:s');
        $user_id = $this->get_login_user_id();
        $param_arr = array($current_date, $this->_body['user_lattitude'], $this->_body['user_longitude'], $user_id
            , $current_date, $current_date, $this->_body['activity_id']);
        $stmt = $this->db->query_execute('Update `tbl_deals_activity` set end_date=?,activity_end_lat=?,activity_end_lng=?,modified_by=?
            ,last_modified=?, activity_duration = TIME_FORMAT(TIMEDIFF(?,start_date), "%H:%i") where activity_id = ? ', $param_arr);
        die(json_encode(array('msg' => 'meeting ended successfully.')));
    }

    //
    public function update_customer_visit() {
        if (empty($this->_body['activity_id']) || empty($this->_body['activity_note']))
            $this->die_error('send note and activity id!');
        $current_date = date('Y-m-d H:i:s');
        $user_id = $this->get_login_user_id();
        $param_arr = array($this->_body['activity_note'], $user_id, $current_date, $this->_body['activity_id']);
        $stmt = $this->db->query_execute('Update `tbl_deals_activity` set activity_notes = ?,modified_by=?,last_modified=? where activity_id = ? ', $param_arr);
        die(json_encode(array('msg' => 'meeting note updated successfully.')));
    }

}
