<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Site extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->model('customer_model');
        $this->load->model('common');
    }

    public function index()
    {
        $userId = $this->session->userdata('session_data')['userId'];
        $machines = $this->common->readdatafromcollectionbetween("Machines", "userId", "=", $userId);
        
        $myMachines = array();
        foreach($machines as $key => $machine) {
            $myMachines[$key] = $machine;
            $location = $this->common->readdatadocument("Locations", $machine['locationId']);
            $myMachines[$key]['location'] = $location;
        }
        
        uasort($myMachines, function($a, $b) {
            return strcmp($a['type'], $b['type']);
        });
        
        $data['myMachines'] = $myMachines;

        $this->template->template_render('home', $data);
    }

    public function login()
    {
        $this->load->view('login');
    }
    
    public function dologin()
	{
		$email = $this->input->post("email");
		$password = $this->input->post("password");

		$firebase = $this->firebase->init();

		$auth = $firebase->createAuth();
		try {
		
            $signInResult = $auth->signInWithEmailAndPassword($email, $password);
            $my = $signInResult->data();


            if (!empty($my["idToken"] )) {

                $session_data = array(
                    'userId' => $my["localId"],
                    'name' => $my["displayName"],
                    'email' => $my["localId"],
                    'firebaseToken' => $my["idToken"]
                );
                $this->session->set_userdata('session_data', $session_data);

                redirect(base_url('site/'));
            } else {
                $errormsg = 'Invalid email and/or password';
                $this->session->set_flashdata('errorTitle', 'Error!');

                $this->session->set_flashdata('errorMessage', $errormsg);   
                redirect(base_url('login'));
            }		
        } catch (Exception $e) {
            $errormsg = 'Invalid email and/or password';
            $this->session->set_flashdata('errorTitle', 'Error!');

            $this->session->set_flashdata('errorMessage', $errormsg);   
            redirect(base_url('login'));
        }	
	}

    public function signup()
    {
        $this->load->view('signup');
    }

    public function dosignup()
	{
		$data = $this->input->post();
		$userId = time();
		$response = $this->customer_model->add_customer($data);
		if ($response) {
			$this->session->set_flashdata('successTitle', 'Good Job!');
			$this->session->set_flashdata('successMessage', 'You have successfully created your account');
			redirect(base_url('site/'));
		} else {
			$errormsg = 'Email already Exists';
			$this->session->set_flashdata('errorTitle', 'Error!');

			$this->session->set_flashdata('errorMessage', $errormsg);
			redirect(base_url('site/signup'));
		}
	}
	

    public function addMachine()
    {
        $userId = $this->session->userdata('session_data')['userId'];
        $data["locations"] = $this->common->readdatafromcollectionbetween("Locations", "userId", "=", $userId, "isActive", "=", true);
        uasort($data["locations"], function($a, $b) {
            return strcmp($a['name'], $b['name']);
        });
        $this->template->template_render('add-machine', $data);
    }

    public function doaddmachine()
    {
        $userId = $this->session->userdata('session_data')['userId'];

        $firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();

        $image_url = '';

        if ($_FILES['image']['tmp_name'] != '') {
            $name = "Machines/machine" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $image_url = 'https://storage.googleapis.com/clawmaster-21035.appspot.com/'.$name;
        }

        $data = $this->input->post();
        $data['userId'] = $userId;
        $data['image'] = $image_url;
        $data['isActive'] = true;
        $data['createdDate'] = time();
        $data['netCommission'] = $data['netCommission'] ? true : false;
        $data['handCount'] = $data['handCount'] ? true : false;
        $this->common->addnewdatamodel("Machines", $data);
        $this->session->set_flashdata('successTitle', 'Good Job!');
		$this->session->set_flashdata('successMessage', 'Machine has been added successfully');
        redirect(base_url('site/addMachine'));
    }

    public function machineInfo($machineId)
    {
        $data["machine"] = $this->common->readdatadocument("Machines", $machineId);
        $data["location"] = $this->common->readdatadocument("Locations", $data["machine"]["locationId"]);
        $data["machineId"] = $machineId;
        $this->template->template_render('machine-info', $data);
    }

    public function addcollection() {
        $userId = $this->session->userdata('session_data')['userId'];
        $data = $this->input->post();
        $docId = time();
        $data["createdDate"] = $docId;
        $data["userId"] = $userId;
        
        $this->common->adddatamodel("Collections", $docId, $data);
        
        $this->session->set_flashdata('successTitle', 'Collection Saved!');
		$this->session->set_flashdata('successMessage', 'Collection has been added for this machine');
        redirect(base_url('site/reports'));
    }

    public function locations()
    {
        $userId = $this->session->userdata('session_data')['userId'];

        $locations = $this->common->readdatafromcollectionbetween("Locations", "userId", "=", $userId, "isActive", "=", true);
        $myLocations = array();
        foreach($locations as $key => $location) {
            $myLocations[$key] = $location;
            $totalMachines = $this->common->readnumberofdocumentsincollectionbetween("Machines", "locationId", "=", $key);
            $myLocations[$key]['totalMachines'] = $totalMachines;
        }

        uasort($myLocations, function($a, $b) {
            return strcmp($a['name'], $b['name']);
        });


        $data['myLocations'] = $myLocations;

        
        $this->template->template_render('locations', $data);
    }
    

    public function addlocation()
    {
        $userId = $this->session->userdata('session_data')['userId'];

        $firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();

        $image_url = '';

        if ($_FILES['image']['tmp_name'] != '') {
            $name = "Locations/location" . rand() . time() . $_FILES['image']['name'];
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['image']['tmp_name']),
                [
                  'name' => $name,
                  'predefinedAcl' => 'publicRead'
                ]
              );
              $image_url = 'https://storage.googleapis.com/clawmaster-21035.appspot.com/'.$name;
        }

        $data = $this->input->post();
        $data['userId'] = $userId;
        $data['image'] = $image_url;
        $data['isActive'] = true;
        $data['createdDate'] = time();
        $this->common->addnewdatamodel("Locations", $data);
        $this->session->set_flashdata('successTitle', 'Good Job!');
		$this->session->set_flashdata('successMessage', 'Location has been added successfully');
        redirect(base_url('site/locations'));
    }

    public function archiveLocation($locationId)
    {
		$data["isActive"] = false;
		$response = $this->common->updatedatamodel("Locations", $locationId, $data);
        if($response) {
            $this->session->set_flashdata('successTitle', 'Done!');
		    $this->session->set_flashdata('successMessage', 'Location has been archived successfully');
        }
        redirect(base_url('site/locations'));
    }

    public function reports()
    {
        $userId = $this->session->userdata('session_data')['userId'];
        
        $reports = $this->common->readdatafromcollectionbetween('Collections', 'userId', '=', $userId);

        $myReports = array();
        foreach($reports as $key => $report) {
            $myReports[$key] = $report;
            $machine = $this->common->readdatadocument("Machines", $report['machineId']);
            $myReports[$key]['machine'] = $machine;
        }

        
        uasort($myReports, function($a, $b) {
            return strcmp($b['createdDate'], $a['createdDate']);
        });
        
        $data['reports'] = $myReports;
        
        $this->template->template_render('reports', $data);
    }

    public function deleteReport($reportId)
    {
		$response = $this->common->deletedatamodel("Collections", $reportId);
        if($response) {
            $this->session->set_flashdata('successTitle', 'Reprot Deleted!');
		    $this->session->set_flashdata('successMessage', 'Report has been deleted successfully');
        }
        redirect(base_url('site/reports'));
    }

    public function smartRoute()
    {
        $this->template->template_render('smart-route');
    }

    public function profile()
    {
        $this->template->template_render('profile');
    }

    public function logout()
	{
		// Removing session data
		$sess_array = array('userId' => '');
		$this->session->unset_userdata('session_data', $sess_array);
		$this->session->sess_destroy();
        $this->session->set_flashdata('successTitle', 'Good Bye!');
		$this->session->set_flashdata('successMessage', 'Successfully Logged out');
		redirect(base_url('site/login'));
	}


}