<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Exception;

class Common extends Model
{

    public $folder_provider = "provider";
    public $folder_service = "service";
    public $folder_complaint = "complaint";
    public $folder_story = "story";

    // Image Functions
    public function saveImage($org_name, $folder, $prefix = "")
    {
        try {
            $img_ext = $org_name->getClientOriginalExtension();
            $filename = $prefix . date('d_m_Y_') . rand(1111, 9999) . '.' . $img_ext;
            $org_name->move(base_path('storage/app/public/' . $folder), $filename);

            return $filename;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function imageNameToUrl($array, $column, $folder)
    {
        try {

            $appName = Config::get('app.image_url');

            foreach ($array as $key => $value) {

                if (isset($value[$column]) && $value[$column] != "") {

                    if ($folder == "user") {

                        if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                            $value[$column] = $appName . $folder . '/' . $value[$column];
                        } else {
                            $value[$column] = asset('assets/imgs/default.png');
                        }
                    } else {

                        if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                            $value[$column] = $appName . $folder . '/' . $value[$column];
                        } else {
                            $value[$column] = asset('assets/imgs/no_img.png');
                        }
                    }
                } else {

                    if ($folder == "user") {
                        $value[$column] = asset('assets/imgs/default.png');
                    } else {
                        $value[$column] = asset('assets/imgs/no_img.png');
                    }
                }
            }
            return $array;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function deleteImageToFolder($folder, $name)
    {
        try {

            Storage::disk('public')->delete($folder . '/' . $name);
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function fileNameToUrl($array, $column, $folder)
    {
        try {

            $appName = Config::get('app.image_url');

            foreach ($array as $key => $value) {

                if (isset($value[$column]) && $value[$column] != "") {

                    if ($folder == "user") {

                        if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                            $value[$column] = $appName . $folder . '/' . $value[$column];
                        } else {
                            $value[$column] = "";
                        }
                    } else {

                        if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                            $value[$column] = $appName . $folder . '/' . $value[$column];
                        } else {
                            $value[$column] = "";
                        }
                    }
                } else {
                    $value[$column] = "";
                }
            }
            return $array;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function getImage($folder = "", $name = "")
    {
        try {

            $appName = Config::get('app.image_url');

            if ($folder != "" && $name != "") {
                if ($folder == "user") {

                    if (Storage::disk('public')->exists($folder . '/' . $name)) {
                        $name = $appName . $folder . '/' . $name;
                    } else {
                        $name = asset('assets/imgs/default.png');
                    }
                } else {

                    if (Storage::disk('public')->exists($folder . '/' . $name)) {
                        $name = $appName . $folder . '/' . $name;
                    } else {
                        $name = asset('assets/imgs/no_img.png');
                    }
                }
            } else {
                if ($folder == "user") {
                    $name = asset('assets/imgs/default.png');
                } else {
                    $name = asset('assets/imgs/no_img.png');
                }
            }
            return $name;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function getVideo($folder = "", $name = "")
    {
        try {

            $appName = Config::get('app.image_url');

            if ($folder != "" && $name != "") {
                if (Storage::disk('public')->exists($folder . '/' . $name)) {
                    $name = $appName . $folder . '/' . $name;
                } else {
                    $name = "";
                }
            } else {

                $name = "";
            }
            return $name;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }

    // Basic Function
    public function user_name($string)
    {
        $rand_number = rand(1111, 9999);
        $user_name = '@' . $string . '_' . $rand_number;

        $check = User::where('user_name', $user_name)->first();
        if (isset($check) && $check != null) {
            $this->user_name($string);
        }
        return $user_name;
    }
    public function in_charge_user_name($string)
    {
        $rand_number = rand(1111, 9999);
        $user_name = '@' . $string . '_' . $rand_number;

        $check = In_Charge::where('user_name', $user_name)->first();
        if (isset($check) && $check != null) {
            $this->in_charge_user_name($string);
        }
        return $user_name;
    }
    public function checkHashTag($hashTag)
    {
        try {

            if (strpos($hashTag, '#') !== false) {

                $remove = substr($hashTag, strpos($hashTag, '#'));
                $tag = explode('#', $remove);

                $id = [];
                if (count($tag) > 0) {
                    foreach ($tag as $key => $value) {

                        if ($value && $value != "") {

                            $value = ltrim($value);
                            $tag = explode(' ', $value)[0];

                            $row = Hashtag::where('name', $tag)->first();
                            if (isset($row['id'])) {

                                $id[] = $row['id'];
                                $row->increment('total_used', 1);
                            } else {

                                $data['name'] = $tag;
                                $data['total_used'] = 1;
                                $data['status'] = 1;
                                $hashtag_id = Hashtag::insertGetId($data);
                                $id[] = $hashtag_id;
                            }
                        }
                    }
                    return $id;
                }
            } else {
                return array();
            }
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function SetSmtpConfig()
    {
        $smtp = Smtp_Setting::latest()->first();
        if (isset($smtp) && $smtp != null && $smtp['status'] == 1) {

            if ($smtp) {
                $data = [
                    'driver' => 'smtp',
                    'host' => $smtp->host,
                    'port' => $smtp->port,
                    'encryption' => 'tls',
                    'username' => $smtp->user,
                    'password' => $smtp->pass,
                    'from' => [
                        'address' => $smtp->from_email,
                        'name' => $smtp->from_name
                    ]
                ];
                Config::set('mail', $data);
            }
        }
        return true;
    }
    public function story_expiry()
    {

        $all_data = Story::get();
        $current_time = time();

        foreach ($all_data as $data) {
            $created_time = strtotime($data->created_at);

            $hours_diff = ($current_time - $created_time) / 3600;
            if ($hours_diff >= 24) {

                $data->update(['status' => 0]);
            }
        }
        return true;
    }

    // API's Functions
    public function API_Response($status_code, $message, $array = [], $pagination = '')
    {
        try {
            $data['status'] = $status_code;
            $data['message'] = $message;

            if ($status_code == 200) {
                $data['result'] = $array;
            }

            if ($pagination) {
                $data['total_rows'] = $pagination['total_rows'];
                $data['total_page'] = $pagination['total_page'];
                $data['current_page'] = $pagination['current_page'];
                $data['more_page'] = $pagination['more_page'];
            }
            return $data;
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
    public function more_page($current_page, $page_size)
    {
        try {
            $more_page = false;
            if ($current_page < $page_size) {
                $more_page = true;
            }
            return $more_page;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function pagination_array($total_rows, $page_size, $current_page, $more_page)
    {
        try {
            $array['total_rows'] = $total_rows;
            $array['total_page'] = $page_size;
            $array['current_page'] = (int) $current_page;
            $array['more_page'] = $more_page;

            return $array;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    function get_complaint_content($complaint_id)
    {
        try {

            $content = Complaint_Img::where('complaint_id', $complaint_id)->get();
            for ($i = 0; $i < count($content); $i++) {

                if ($content[$i]['content_type'] == 1) {
                    $content[$i]['content_url'] = $this->getImage($this->folder_complaint, $content[$i]['content_url']);
                } else {
                    $content[$i]['content_url'] = $this->getVideo($this->folder_complaint, $content[$i]['content_url']);
                    $content[$i]['thumbnail_image'] = $this->getVideo($this->folder_complaint, $content[$i]['thumbnail_image']);
                }
            }
            return $content;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function is_like($user_id, $complaint_id)
    {
        try {

            $is_like = 0;
            $data = Like::where('complaint_id', $complaint_id)->where('user_id', $user_id)->where('status', 1)->first();
            if ($data != null && isset($data)) {
                $is_like = 1;
            }
            return $is_like;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function is_dislike($user_id, $complaint_id)
    {
        try {

            $is_dislike = 0;
            $data = Like::where('complaint_id', $complaint_id)->where('user_id', $user_id)->where('status', 2)->first();
            if ($data != null && isset($data)) {
                $is_dislike = 1;
            }
            return $is_dislike;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function getHashTag($hashTag)
    {
        try {
            // $tag_id = explode(',', $hashTag);
            // $hashtage = [];
            // if (count($tag_id) > 0) {
            //     foreach ($tag_id as $key => $value) {
            //         $row = Hashtag::where('id', $value)->first();
            //         if (isset($row->id)) {

            //             $hashtage[] = $row;
            //         }
            //     }
            //     return $hashtage;
            // } else {
            //     return $hashtage;
            // }
            $ids = explode(',', $hashTag);
            $hashtags = Hashtag::whereIn('id', $ids)->get();
            $hashtagString = '';
            foreach ($hashtags as $hashtag) {
                $hashtagString .= '#' . $hashtag->name;
            }
            return $hashtagString;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_sub_incharge($id)
    {
        try {

            $data = Sub_In_Charge::where('id', $id)->where('department_id', '!=', 0)->where('service_id', '!=', "")->first();
            if ($data != null && isset($data)) {

                return $data;
            }
            return [];
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_in_charge($id)
    {
        try {

            $data = In_Charge::where('id', $id)->where('department_id', '!=', 0)->first();
            if ($data != null && isset($data)) {
                return $data;
            }
            return [];
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function save_notification($type = 0, $recipient_id = 0, $complaint_id = 0, $title = null) // 1- User, 2- Sub In-charge, 3- Admin	
    {
        try {

            $data['type'] = $type;
            $data['recipient_id'] = $recipient_id;
            $data['complaint_id'] = $complaint_id;
            $data['title'] = $title;
            $data['message'] = "";
            $data['image'] = "";
            $notification = Notification::insertGetId($data);

            $toUser = [];
            if ($type == 1) {

                $recipient = User::where('id', $recipient_id)->first();
            } elseif ($type == 2) {
                $recipient = Sub_In_Charge::where('id', $recipient_id)->first();
            } elseif ($type == 4) {
                $recipient = In_Charge::where('id', $recipient_id)->first();
            }

            if (isset($recipient['device_token'])) {

                $toUser[] = $recipient['device_token'];

                $setting = Setting_Data();

                if ($type == 1) {
                    $ONESIGNAL_APP_ID = $setting['onesignal_apid'];
                    $ONESIGNAL_REST_KEY = $setting['onesignal_rest_key'];
                } elseif ($type == 2 || 4) {
                    $ONESIGNAL_APP_ID = $setting['sub_incharge_onesignal_apid'];
                    $ONESIGNAL_REST_KEY = $setting['sub_incharge_onesignal_rest_key'];
                }

                // Device type (1 = Android, 2 = IOS)
                $fields = array();
                if ($recipient['device_type'] == 1) {
                    $fields = array(
                        'app_id' => $ONESIGNAL_APP_ID,
                        'include_android_reg_ids' => $toUser,
                        "isAndroid" => true,
                        "channel_for_external_user_ids" => "push",
                        'headings' => array("en" => App_Name()),
                        'contents' => array("en" => $title),

                    );
                } elseif ($recipient['device_type'] == 2) {
                    $fields = array(
                        'app_id' => $ONESIGNAL_APP_ID,
                        'include_player_ids' => $toUser,
                        "isIos" => true,
                        "channel_for_external_user_ids" => "push",
                        'headings' => array("en" => App_Name()),
                        'contents' => array("en" => $title),
                    );
                }

                $fields = json_encode($fields);

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Authorization: Basic ' . $ONESIGNAL_REST_KEY
                ));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_HEADER, FALSE);
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

                $response = curl_exec($ch);
                curl_close($ch);
                return true;
            }
            return true;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function setemailconfig()
    {
        $smtp = Smtp_Setting::first();
        if (isset($smtp) && $smtp != null && $smtp != false) {
            $data = [
                'driver' => 'smtp',
                'host' => $smtp->host,
                'port' => $smtp->port,
                'encryption' => 'tls',
                'username' => $smtp->user,
                'password' => $smtp->pass,
                'from' => [
                    'address' => $smtp->from_email,
                    'name' => env('APP_NAME'),
                ]
            ];
            Config::set('mail', $data);
        }
    }
    function Send_Mail($type, $email)
    {
        try {

            $this->setemailconfig();
            $smtp = Smtp_Setting::first();
            if (isset($smtp) && $smtp != false && $smtp['status'] == 1) {

                if ($type == 1) {
                    $title = App_Name() . " - Register";
                    $body = "Welcome to " . App_Name() . " App & Enjoy this app.";
                } else if ($type == 2) {
                    $title = App_Name() . " - Login";
                    $body = "Welcome to " . App_Name() . " App & Enjoy this app.";
                } else if ($type == 3) {
                    $title = App_Name() . " - Request Submitted";
                    $body = "Thank you for using " . App_Name() . "! Your request has been successfully submitted.";
                } else if ($type == 4) {
                    $title = App_Name() . " - Your Request is in Progress";
                    $body = "Good news! Department has started working on your request. We will notify you upon completion.";
                } else if ($type == 5) {
                    $title = App_Name() . " - Request Canceled Notification";
                    $body = "We regret to notify you that your request has been canceled. Feel free to contact us for further clarification.";
                } else if ($type == 6) {
                    $title = App_Name() . " - Request Completed";
                    $body = "Your request has been successfully completed. Thank you for using " . App_Name() . ".";
                } else {
                    return true;
                }
                $details = [
                    'title' => $title,
                    'body' => $body
                ];

                Mail::to($email)->send(new \App\Mail\mail($details));
                return true;
            } else {
                return true;
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_Subin_charge_name($department_id, $service_id)
    {
        try {

            $data = Sub_In_Charge::where('department_id', $department_id)->where('service_id', $service_id)->first();
            if ($data != null && isset($data)) {
                return $data['full_name'];
            }
            return "";
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function BasicNotiConfiguration($type)
    {
        if ($type != null) {
            return Notification_Configuration::where('type', $type)->first();
        }
        return [];
    }
}
