<?php

class GroupSettingController extends AppController
{
    var $uses = array(
        'GroupSetting'
    );

    public $components = array('RequestHandler', 'Permission');

    private $platform = "3" ;  // 1 = Android, 2 = iPhone, 3 = Web
    private $app_version = "2";
    private $version = 0;
    private $application_version = "3.2";
    private $validation_status = "-1";

    public function beforeRender()
    {
        parent::beforeRender();
    }

    public function addPermission()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;

            $response = [
                'status' => false,
                'message' => 'Failed'
            ];

            $request = $this->basicRequest();
            $user_id = $this->Session->read('userData.id');
            $profile_id = $this->Session->read('userData.profile_id');

            $request["expense_id"] = $this->data["expense_id"];
            $request["unique_url"] = $this->data["unique_url"];
            $request["user_id"] = $user_id;
            $request["profile_id"] = $profile_id;

            $request["addPermissions"] = [];
            $request["modifyPermissions"] = [];
            $request["deletePermissions"] = [];

            $operation = [
                "email" => $this->data["email"],
                "name" => $this->data["name"],
                "role" => $this->data["permission"]
            ];

            if ($this->data["operation_type"] == $this->operation_type['ADD']) {
                $request["addPermissions"][] = $operation;
            } else if ($this->data["operation_type"] == $this->operation_type['EDIT']) {
                $request["modifyPermissions"][] = $operation;
            } else if ($this->data["operation_type"] == $this->operation_type['DELETE']) {
                $request["deletePermissions"][] = $operation;
            }
            $apiResponse = $this->callAPI(HTTP_SITE_URL . "/Expense/permissions.json", 'POST', json_encode($request));

            $apiResponseArr = json_decode($apiResponse, true);
            if (isset($apiResponseArr['response']['status']) && ($apiResponseArr['response']['status'] == '+000')) {
                $response['status'] = true;
                $response['message'] = 'Saved successfully.';
                $response['permissions'] = $apiResponseArr['response']['data']['settings']['permissions'];
            }else{
                $response['message'] = isset($apiResponseArr['response']['status_desc'])
                    ? $apiResponseArr['response']['status_desc']
                    : $response['message'];
            }
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        }
        else {
            throw new BadRequestException('Invalid request method');
        }
    }

    public function addRestriction()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;

            $profile_id = $this->Session->read('userData.profile_id');
            $user_id = $this->Session->read('userData.id');

            $response = [
                'status' => false,
                'message' => 'Failed'
            ];

            $request = $this->basicRequest();

            $request["expense_id"]      = $this->data["expense_id"];
            $request["unique_url"]      = $this->data["unique_url"];
            $request["user_id"]         = $user_id;
            $request["profile_id"]      = $profile_id;
            $request["is_restricted_mode"] = $this->data["mode"];

            $apiResponse = $this->callAPI(HTTP_SITE_URL . "/Expense/restriction.json", 'POST', json_encode($request));
            $apiResponseArr = json_decode($apiResponse, true);
            if (isset($apiResponseArr['response']['status'])) {
                $response['restricted_mode'] = false;
                $response['status'] = true;
                if ($apiResponseArr['response']['status'] == '+000') {
                    $response['message'] = "Restricted Mode saved successfully.";
                    if($apiResponseArr['response']['GroupSetting']['is_restricted_mode'] == 1) {
                        $response['restricted_mode'] = true;
                    }
                }
                if($apiResponseArr['response']['status'] == '-1') {
                    $response['message'] = $apiResponseArr['response']['status_desc'];
                }

            }
            header('Content-Type: application/json');
            echo json_encode($response);
            exit;
        } else {
            throw new BadRequestException('Invalid request method');
        }
    }

    public function fixed_price()
    {
        $object = $this->request->input('json_decode');
        if (!empty($object)) {
            $data = $this->objectToArray($object);
        }
        if (!isset($data['skip_process_validation'])) {
            list($data, $status, $status_desc, $error) = $this->processValidation();
        }
        if (!empty($data) && empty($status)) {
            list($status, $status_desc, $error) = $this->requestValidate($data);
        }
        if (empty($status)) {
            $object = json_decode(json_encode($object), true);
            list($status, $status_desc, $expObj) = $this->validateUniqueUrl($object['unique_url']);
        }

        $input = array();

        if (empty($status)) {
            $status_message =  [
                'code' => "061",
                'message' => 'Error: Expense not found.'
            ];
            $status = $status_message['code'];
            $status_desc = $status_message['message'];
            $expense = $this->Expense->find('first', array(
                'conditions' => array('Expense.id' => $object['expense_id'], 'Expense.unique_url' => $object['unique_url'])
            ));
            $this->loadModel('GroupSettings');
            //check expense_id and unique_url is exist or not
            $groupSettings = $this->GroupSetting->find('first', array(
                'conditions' => array('GroupSetting.expense_id' => $object['expense_id'], 'GroupSetting.unique_url' => $object['unique_url'])
            ));

            if (!empty($expense['Expense']) && !empty($groupSettings['GroupSetting'])) {
                $is_add_possible = false;
                if(!empty($expense['Expense']['user_id']) || $expense['Expense']['create_user'] != 'system') {
                    if($expense['Expense']['user_id'] == $object['user_id'] && $groupSettings['GroupSetting']['is_restricted_mode'] == 1){
                        $is_add_possible = true; // only owner can add the fixed price
                    }
                    if($groupSettings['GroupSetting']['is_restricted_mode'] == 0){
                        $is_add_possible = true; // anyone can add the fixed price
                    }
                }
                if($is_add_possible){
                    $data['id'] = $groupSettings['GroupSetting']['id'];
                    $data['version'] = $groupSettings['GroupSetting']['version'] + 1;
                    $data['is_fixed_price'] = (isset($object['is_fixed_price']) && $object['is_fixed_price'] >0) ? true : false;
                    $data['expense_id'] = $groupSettings['GroupSetting']['expense_id'];
                    $data['unique_url'] = $groupSettings['GroupSetting']['unique_url'];

                    if (!empty($expense['Expense'])) {
                        $expense['Expense']['version'] = $expense['Expense']['version'] + 1;
                    }
                    $this->GroupSetting->save($data);
                    $this->Expense->save($expense);
                    $groupSettings['GroupSetting']['is_fixed_price'] = $object['is_fixed_price'];
                    $status_desc = "SUCCESS";
                    $status = "+000";
                    $input['GroupSetting'] = $groupSettings['GroupSetting'];

                }
            }


        }

        if ($status != "+000") {
            $this->processResponse($input, $data, $status, $status_desc);
        } else {
            $this->updateFirebase($object['unique_url']);
            $input["status"] = $status;
            $input["status_desc"] = $status_desc;
            $input["api_version"] = 3;

            $this->set(array(
                'response' => $input,
                '_serialize' => array('response')
            ));
        }
    }

    public function requestValidate($object)
    {

        //check validity
        $error = "";
        $error_desc = "";
        $expObj = array();

        if (empty($object['expense_id'])) {
            $error = $this->validation_status;
            $error_desc = "expense_id must be provided!";
            $expObj['expense_id'] = $error_desc;
        }
        if (empty($object['unique_url'])) {
            $error = $this->validation_status;
            $error_desc = "unique_url must be provided!";
            $expObj['unique_url'] = $error_desc;
        }
        if (!empty($object['user_id']) && !is_numeric($object['user_id'])) {
            $error = $this->validation_status;
            $error_desc = 'user_id must be provided as numeric.';
        }
        if (!isset($object['is_fixed_price'])) {
            $error = $this->validation_status;
            $error_desc = "is_fixed_price must be provided!";
            $expObj['is_fixed_price'] = $error_desc;
        }
        return array($error, $error_desc, $expObj);
    }

    private function basicRequest(){
        $deviceData = $this->deviceData();
        $request = [
            "platform"             => $this->platform, // 1 = Android, 2 = iPhone, 3 = Web
            "app_version"          => $this->app_version, // optional
            "version"              => $this->version, // optional
            "application_version"  => $this->application_version, // optional
            "device_id"            => $deviceData['device_id'],
            "random_number"        => $deviceData['random_number'],
            "access_token"         => $deviceData['access_token'],
        ];
        return $request;
    }




}
