<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\RoadItemsProject;
use App\Models\RoadPatrol;
use App\Models\RoadObserved;
use App\Models\InfoItem;
use App\Models\User;
use App\Models\HttpErorrsList;
use App\Models\SafetyAndPrivacy;
use GuzzleHttp\Client;
use Auth;
use App\Models\EdarateOstani;


class GeneralController extends Controller
{
    public function errors()
    {
        $post = array(
            // 'username' => env("PAYMENT_USERNAME"),
            // 'password' => env("PAYMENT_PASSWORD"),
            // 'amount'   => $final_amount,
            // 'serial'   => "12345",
            // 'type'   => 1,
            // 'instanceid'   => 123,
            // 'ownerid'   => $driver_national_code,
            // 'calculationBox'   =>  "{\"rows\":[{\"amount\":". $final_amount .",\"code\":\"7070021060000015\"}]}"
        );
        // 204063776282400001230003985031/4001063704010676
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://payment.rmto.ir/acc/rest/payid/track2/".env("PAYMENT_USERNAME")."/".env("PAYMENT_PASSWORD")."/204063776282400001230003985031");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_POST, true);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        $response = curl_exec($ch);
        curl_close($ch);
        // dd("http://payment.rmto.ir/acc/rest/payid/track2/".env("PAYMENT_USERNAME")."/".env("PAYMENT_PASSWORD")."/{204063776282400001230003985031}");
        return $response;



        // $client = new \GuzzleHttp\Client();

        // $url = "http://payment.rmto.ir/acc/rest/payid/gen";

        // // $post = [
        //     $body['Username'] = 'cspay';
        //     $body['Password'] = 'cspay123';
        //     $body['Amount']   = 10;
        //     $body['Serial']   = 10;
        //     $body['Type']   = 1;
        //     $body['Instanceid']   = 358063754282400001100000010676;
        //     $body['Ownerid']   = 1450103456;
        //     $body['calculationBox']   =  "{\"rows\":[{\"amount\":10,\"code\":\"7070021060000015\"}]}";

        // [
            //     "rows" =>[
            //         ["amount" => 10,"code" => "707001"]
            //     ],
            //     // [],
        // ],
        // ];

        // $myBody['name'] = "Demo";

        // $request = $client->post($url,  ['body'=>$body]);

        // $response = $request->send();



        // dd($response);

        // $arrayName = array('' => , );
        $post = array(
                'username' => env("PAYMENT_USERNAME"),
                'password' => env("PAYMENT_PASSWORD"),
                'amount'   => "1000",
                'serial'   => "12345",
                'type'   => 1,
                'instanceid'   => 123,
                'ownerid'   => "1450103456",
                'calculationBox'   =>  "{\"rows\":[{\"amount\":1000,\"code\":\"7070021060000015\"}]}"
            );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://payment.rmto.ir/acc/rest/payid/gen");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
        var_dump($response);
        dd();

        // $tmp = User::with("permissions")->whereHas("permissions", function($q) {
        //     $q->where("id", 140);
        // })->get();

        // dd($tmp);
        $data = [];
        $key_ = 0;
        // try {
        foreach (HttpErorrsList::all() as $key => $value) {
            try {
                $data[] = unserialize(base64_decode($value->value));
            } catch (\Throwable $th) {
                $data[] = $value->id;
            }
        }

        dd($data);
        // } catch (\Throwable $th) {
        //     // return response()->json($key_, 200);
        // }

        echo "<pre>";
        echo var_dump($data);
        echo "</pre>";
    }
    public function getActivityStatistics(Request $request)
    {
        $data = array();

        $road_items = array();
        $road_items['total'] = 0;
        if (auth()->user()->can('create-road-item')) {
            $road_items['operation_cnt'] = RoadItemsProject::where('is_new', 1)
                                            ->where('user_id', auth()->user()->id)
                                            ->where('status', 2)
                                            ->count();

            $road_items['total'] += $road_items['operation_cnt'];
        }

        if (auth()->user()->can('supervise-road-item')) {
            $road_items['supervise_cnt'] = RoadItemsProject::where('is_new', 1)
                                            ->where(function ($query) {
                                                $query->where('status', 0);
                                                // ->orWhere('supervisor_id', auth()->user()->id);
                                            })->count();

            $road_items['total'] += $road_items['supervise_cnt'];
        } elseif (auth()->user()->can('supervise-road-item-province')) {
            if (is_null(auth()->user()->province_id) || !auth()->user()->province_id) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 403);
            }

            $road_items['supervise_cnt'] = RoadItemsProject::where('is_new', 1)
                                            ->where('province_id', auth()->user()->province_id)
                                            ->where(function ($query) {
                                                $query->where('status', 0);
                                                // ->orWhere('supervisor_id', auth()->user()->id);
                                            })
                                            ->count();

            $road_items['total'] += $road_items['supervise_cnt'];
        }elseif (auth()->user()->can('supervise-road-item-by-edareostani')) {
            if (is_null(auth()->user()->edarate_ostani_id) || !auth()->user()->edarate_ostani_id) {
                return response()->json([
                    'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
                ], 403);
            }

            $road_items['supervise_cnt'] = RoadItemsProject::where('is_new', 1)
                                            ->where('province_id', auth()->user()->province_id)
                                            ->whereIn('item', explode(",", EdarateOstani::where('id', auth()->user()->edarate_ostani_id)->first()->items_for_confirm))
                                            ->where(function ($query) {
                                                $query->where('status', 0);
                                                // ->orWhere('supervisor_id', auth()->user()->id);
                                            })
                                            ->count();

            $road_items['total'] += $road_items['supervise_cnt'];
        }

        if (!empty($road_items)) {
            $data['road_items'] = $road_items;
        }
        // road item (end)

        // road patrol (begin)
        $road_patrols = array();
        $road_patrols['total'] = 0;
        // if (auth()->user()->can('add-road-patrol')) {
        //     $road_patrols['operation_cnt'] = RoadPatrol::where('operator_id', auth()->user()->id)
        //                                     ->where('status', 2)
        //                                     ->count();

        //     $road_patrols['total'] += $road_patrols['operation_cnt'];
        // }

        // if (auth()->user()->can('show-road-patrol-supervise-cartable')) {
        //     $road_patrols['supervise_cnt'] = RoadPatrol::where(function ($query) {
        //         $query->where('status', 0);
        //         // ->orWhere('supervisor_id', auth()->user()->id);
        //     })->count();

        //     $road_patrols['total'] += $road_patrols['supervise_cnt'];
        // } elseif (auth()->user()->can('show-road-patrol-supervise-cartable-province')) {
        //     if (is_null(auth()->user()->province_id) || !auth()->user()->province_id) {
        //         return response()->json([
        //             'message' => 'استانی برای شما در سامانه ثبت نشده است!'
        //         ], 403);
        //     }

        //     $road_patrols['supervise_cnt'] = RoadPatrol::where('province_id', auth()->user()->province_id)
        //                                     ->where(function ($query) {
        //                                         $query->where('status', 0);
        //                                         // ->orWhere('supervisor_id', auth()->user()->id);
        //                                     })
        //                                     ->count();

        //     $road_patrols['total'] += $road_patrols['supervise_cnt'];
        // }

        if (!empty($road_patrols)) {
            $data['road_patrols'] = $road_patrols;
        }
        // road patrol (end)

        // road observation (begin)
        $road_observations = array();
        $road_observations['total'] = 0;
        if (auth()->user()->can('show-fast-react')) {
            $road_observations['operation_cnt'] = RoadObserved::where('status', 2)
                                            ->count();

            $road_observations['total'] += $road_observations['operation_cnt'];
        } elseif (auth()->user()->can('show-fast-react-province')) {
            if (is_null(auth()->user()->province_id) || !auth()->user()->province_id) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 403);
            }

            $road_observations['operation_cnt'] = RoadObserved::where('status', 2)
                                             ->where('rms_province_id', auth()->user()->province_id)
                                             ->count();

            $road_observations['total'] += $road_observations['operation_cnt'];
        } elseif (auth()->user()->can('show-fast-react-edarate-shahri')) {
            if (is_null(auth()->user()->edarate_shahri_id)) {
                return response()->json([
                    'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
                ], 403);
            }

            $road_observations['operation_cnt'] = RoadObserved::where('status', 2)
                                            ->where('edarate_shahri_id', auth()->user()->edarate_shahri_id)
                                            ->count();

            $road_observations['total'] += $road_observations['operation_cnt'];
        }

        if (auth()->user()->can('supervise-fast-react')) {
            $road_observations['supervise_cnt'] = RoadObserved::where(function ($query) {
                $query->where('status', 0);
                // ->orWhere('supervisor_id', auth()->user()->id);
            })->count();

            $road_observations['total'] += $road_observations['supervise_cnt'];
        } elseif (auth()->user()->can('supervise-fast-react-province')) {
            if (is_null(auth()->user()->province_id) || !auth()->user()->province_id) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 403);
            }

            $road_observations['supervise_cnt'] = RoadObserved::where('province_id', auth()->user()->province_id)
                                            ->where(function ($query) {
                                                $query->where('status', 0);
                                                // ->orWhere('supervisor_id', auth()->user()->id);
                                            })
                                            ->count();

            $road_observations['total'] += $road_observations['supervise_cnt'];
        }

        if (!empty($road_observations)) {
            $data['road_observations'] = $road_observations;
        }
        // road observation (end)

        // safety and privacy (begin)
        $safety_and_privacy = array();
        // $safety_and_privacy['total'] = 0;
        if (auth()->user()->hasPermissionTo('show-safety-and-privacy-operator-cartable')) {
            $temp_data = SafetyAndPrivacy::selectRaw('count(*) as cnt, step')
                            ->groupby('step')
                            ->orderBy('step')
                            ->get();

        } elseif (auth()->user()->hasPermissionTo('show-safety-and-privacy-operator-cartable-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $temp_data = SafetyAndPrivacy::where('province_id', auth()->user()->province_id)
                            ->selectRaw('count(*) as cnt, step')
                            ->groupby('step')
                            ->orderBy('step')
                            ->get();

        } elseif (auth()->user()->hasPermissionTo('show-safety-and-privacy-operator-cartable-edarate-shahri')) {
            if (is_null(auth()->user()->edarate_shahri_id)) {
                return response()->json([
                    'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $temp_data = SafetyAndPrivacy::where('edare_shahri_id', auth()->user()->edarate_shahri_id)
                            ->selectRaw('count(*) as cnt, step')
                            ->groupby('step')
                            ->orderBy('step')
                            ->get();                                 
        }

        $safety_and_privacy['step_one'] = isset($temp_data[0]) ? $temp_data[0]->cnt : 0;
        $safety_and_privacy['step_two'] = isset($temp_data[1]) ? $temp_data[1]->cnt : 0;
        $safety_and_privacy['step_three'] = isset($temp_data[2]) ? $temp_data[2]->cnt : 0;

        if (!empty($safety_and_privacy)) {
            $data['safety_and_privacy'] = $safety_and_privacy;
        }
        // safety and privacy (end)

        return response()->json(
            $data
        );
    }

    public function getItems()
    {
        return response()->json([
            'data' => InfoItem::select('item as id', 'item_str as name', 'icon')->where('type', 'item')->groupby('item')->get()
        ]);
    }

    public function getSubItems(Request $request, $item)
    {
        return response()->json([
            'data' => InfoItem::where('item', $item)->select('id', 'item', 'item_str', 'sub_item_str as name', 'sub_item_unit as unit', 'needs_image', 'needs_end_point', 'sub_item')->get()
        ]);
    }
}
