<?php

namespace App\Services;

use App\FranchisePostCodes;
use App\Invoices;
use App\Members;

class UAE implements \App\Services\Country {

    public function validatePostalCode($postcode) {
        /*
         * * This function takes in a string, cleans it up, and returns an array with the following information:
         * * ["validate"] => TRUE/FALSE
         * * ["prefix"] => first part of postcode
         * * ["suffix"] => second part of postcode
         */
        // if (preg_match($valid_postcode_exp, strtoupper($postcode))) {

        $postcode = preg_replace('/\s+/', '', $postcode);
        $suffix = substr($postcode, -3);
        $prefix = str_replace($suffix, '', $postcode);

        $output['validate'] = true;
        $output['prefix'] = $postcode;
        $output['suffix'] = "";
        $output['franchise_id'] = 1;
        return $output;
    }

    public function getLatitudeLongitude($postcode) {
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($postcode) . "&key=" . env("GOOGLE_MAP_API_KEY") . "&sensor=false";
        $result_string = file_get_contents($url);
        $result = json_decode($result_string, true);
        $suffix = substr($postcode, -3);
        //var_dump($result);die();
        if (strtolower($result['status']) == "ok") {
            $result1[] = $result['results'][0];
            $result2[] = $result1[0]['geometry'];
            $result3[] = $result2[0]['location'];
            return $result3[0]['lat'] . ',' . $result3[0]['lng'];
        } elseif ($suffix) {
            $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($suffix) . "&key=" . env("GOOGLE_MAP_API_KEY") . "&sensor=false";
            $result_string = file_get_contents($url);
            $result = json_decode($result_string, true);
            if (strtolower($result['status']) == "ok") {
                $result1[] = $result['results'][0];
                $result2[] = $result1[0]['geometry'];
                $result3[] = $result2[0]['location'];
                return $result3[0]['lat'] . ',' . $result3[0]['lng'];
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    public function getAreaOrders($from, $to) {


        $model = Invoices::whereBetween("ws_invoices.CreatedDateTime", [$from, $to])
                ->groupBy("AreaName")
                ->where('OrderStatus', "!=", 'Cancel')
                ->leftJoin('ws_franchises as f', 'f.PKFranchiseID', '=', 'ws_invoices.FKFranchiseID')
                ->select(\DB::raw('count(PKINvoiceID) as orders'), \DB::raw('sum(GrandTotal) as total'), "AreaName", "f.Title")
                ->get();

        $codes = array();
        $total = 0;
        $totalOrders = 0;


        foreach ($model as $row) {

            $prefix = strtoupper(trim($row->PostalCode));

            if ($prefix == "") {
                $prefix = strtoupper(trim($row->AreaName));
            }

            if (key_exists($prefix, $codes)) {
                $codes[$prefix]["orders"] = $codes[$prefix]["orders"] + $row->orders;
                $codes[$prefix]["total"] = $codes[$prefix]["total"] + $row->total;
            } else {
                $codes[$prefix]["orders"] = $row->orders;
                $codes[$prefix]["total"] = $row->total;
            }
            $codes[$prefix]["franchise"] = $row->Title;
            $totalOrders += $row->orders;
            $total += $row->total;
        }
        $data['data'] = $codes;
        $data['view'] = "uae";
        $data['text'] = "Area";
        $data['total'] = $total;
        $data['orders'] = $totalOrders;

        return $data;
    }

    public function getAreaMembers($from, $to) {

        $model = Members::whereBetween("CreatedDateTime", [$from, $to])
                ->groupBy("PostalCode")
                ->select(\DB::raw('count(PKMemberID) as members'), "PostalCode", "AreaName")
                ->get();
        $codes = array();
        $total = 0;

        foreach ($model as $row) {
            $prefix = strtoupper(trim($row->PostalCode));

            if ($prefix == "") {
                $prefix = strtoupper(trim($row->AreaName));
            }

            if (key_exists($prefix, $codes)) {
                $codes[$prefix]["members"] = $codes[$prefix]["members"] + $row->members;
            } else {
                $codes[$prefix]["members"] = $row->members;
            }
            $total += $row->members;
        }

        $data['data'] = $codes;
        $data['view'] = "uk";
        $data['text'] = "Area";
        $data['total'] = $total;
        return $data;
    }

    public function getAreasList() {
        $model = Invoices::select("Town")->get();
        $list = array();
        foreach ($model as $row) {
            $val = trim($row->Town);
            $list[$val] = $val;
            
        }
        $data["title"]="Area";
        $data["list"]=$list;
        
        return $data;
    }
    
    
    public function ordersByLocations($from, $to, $locations) {

        $model = Invoices::whereBetween("ws_invoices.CreatedDateTime", [$from, $to]);
        $model = $model->where('OrderStatus', "!=", 'Cancel');


        if(!empty($locations)) {
            $model = $model->where(function ($query) use ($locations) {

                foreach($locations as $location) {
                    $query->orWhere('PostalCode', "Like", $location.'%');
                }
            });
        }
        return $model->get();
    }
    
}
