<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\City;
use App\Models\Category;
use App\Models\Setting;
use App\Models\PaymentGateway;
use App\Models\Orders;
use App\Models\Package;
use App\Models\Parameter;
use App\Models\Profiles;
use App\Models\Popular_package;
use Session;
use App\Models\News;
use Hash;
use Mail;
use Auth;
use DateTimeZone;
use DateTime;
use App\Models\Contactus;
use DataTables;

class AdminController extends Controller
{
    public function show_login(){
        $setting = Setting::find(1);
        return view("admin.login")->with("setting",$setting);
    }
    public function post_login(Request $request){
        $checkuser=User::where("email",$request->get("email"))->where("password",$request->get("password"))->where("user_type",'1')->first();      
        if($checkuser){
            Auth::login($checkuser, true);
            Session::put("id",$checkuser->id); 
            Session::put("admin_profile",$checkuser->profile_pic); 
            Session::put("admin",1); 
            Session::put("name",$checkuser->name); 
            $setting = Setting::find(1); 
            Session::put("is_rtl",$setting->is_rtl);
            Session::put("is_demo",$setting->is_demo);
            Session::put("logo",asset('public/img').'/'.$setting->footer_logo);
            Session::put("favicon",asset('public/img').'/'.$setting->favicon);
            if($request->get("rem_me")==1){
                setcookie('email', $request->get("email"), time() + (86400 * 30), "/");
                setcookie('password',$request->get("password"), time() + (86400 * 30), "/");
                setcookie('remember',1, time() + (86400 * 30), "/");
            } 
            return redirect()->route("admin-dashboard");
        }else{
            Session::flash('message',__('message.Login credentials are wrong')); 
            Session::flash('alert-class', 'alert-danger');
            return redirect()->back();
        }
    }
    public function show_dashboard(){ 
        $totalcategory= count(Category::where('is_deleted','0')->get());
        $totalcity= count(City::get()); 
        $getcurrency = Setting::find(1);
        $currency = explode("-",$getcurrency->currency);
        $totalsales = Orders::sum('final_total');   
        $totalorder = count(Orders::all()); 
        $completeorder = count(Orders::where("status","7")->get());  
        $pendingorders = count(Orders::whereIn("status",array(2,6,5))->get());
        $totalusers = count(User::where("user_type","3")->get());
        $totalmanager = count(User::where("user_type","2")->get());  
        $totalpackage = count(Package::all());
        $totalprofile = count(Profiles::all());
        $totalparameter = count(Parameter::all());
        $totalpopular = count(Popular_package::all());

        return view("admin.dashboard")->with("totalcategory",$totalcategory)->with("totalcity",$totalcity)->with("totalsales",$totalsales)->with("currency",$currency[1])->with("totalorder",$totalorder)->with("completeorder",$completeorder)->with("pendingorders",$pendingorders)->with("totalusers",$totalusers)->with("totalmanager",$totalmanager)->with("totalpackage",$totalpackage)->with("totalprofile",$totalprofile)->with("totalparameter",$totalparameter)->with("totalpopular",$totalpopular);
    }
     public function logout(){
        // Auth::logout();
        session::forget('admin');
        return redirect()->route('admin-login');
    }
     public function show_admin_profile(){
        return view("admin.editprofile");    
    }
    public function show_update_admin_profile(Request $request){
        $store = User::find(Auth::id());
       // $store->username = $request->get("username");
        $store->name = $request->get("name");
        $store->email = $request->get("emailId");
        if($request->file("upload_image")){
            if(Auth::user()->profile_pic!=""){
                $this->removeImage('profile/' . $store->profile_pic);
            }             
            $store->profile_pic = $this->fileuploadFileImage($request,'profile','upload_image');
        }        
        $store->save();
        Session::flash('message',__('message.Profile Update Successfully')); 
        Session::flash('alert-class', 'alert-success');
        return redirect()->back();
    }
    public function change_password(Request $request){
        return view("admin.changepassword");
    }

    public function update_check_admin_password($val){
        $admin = User::find(1);
        if($val== $admin->password){
            return 0;
        }
        return 1;
    }

    public function update_check_user_password($val){
        $user = User::find(Auth::id());
        if(Hash::check($val, $user->password)){
            return 0;
        }
        if($val== $user->password){
            return 0;
        }
        return 1;
    }
    public function show_update_admin_change_password(Request $request){
        $store = User::find(Auth::id());
        $store->password = $request->get("newPassword");
        $store->save();
        Session::flash('message',__('message.Password Update Successfully')); 
        Session::flash('alert-class', 'alert-success');
        return redirect()->back();
    }

    
   static public function generate_timezone_list(){
    static $regions = array(
      DateTimeZone::AFRICA,
      DateTimeZone::AMERICA,
      DateTimeZone::ANTARCTICA,
      DateTimeZone::ASIA,
      DateTimeZone::ATLANTIC,
      DateTimeZone::AUSTRALIA,
      DateTimeZone::EUROPE,
      DateTimeZone::INDIAN,
      DateTimeZone::PACIFIC,
    );

    $timezones = array();
    foreach($regions as $region) {
      $timezones = array_merge($timezones, DateTimeZone::listIdentifiers($region));
    }

    $timezone_offsets = array();
    foreach($timezones as $timezone) {
      $tz = new DateTimeZone($timezone);
      $timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
    }

    asort($timezone_offsets);

    $timezone_list = array();
    
    foreach($timezone_offsets as $timezone=>$offset){
      $offset_prefix = $offset < 0 ? '-' : '+';
      $offset_formatted = gmdate('H:i', abs($offset));
      $pretty_offset = "UTC${offset_prefix}${offset_formatted}";
      $timezone_list[] = "(${pretty_offset}) $timezone";
    }

    return $timezone_list;
    ob_end_flush();
  }
    public function showsetting($id){
       $setting=Setting::find(1);
       $payment=PaymentGateway::all();
        $getallkeys = PaymentGateway::all();
        $ls = array();
        foreach($getallkeys as $g){
            $ls[$g->payment_gateway_name."_".$g->key_name] = $g->meta_value;
        }
        $timezone_list = $this->generate_timezone_list();
        
       return view("admin.setting.setting")->with("id",$id)->with("data",$setting)->with("payment",$ls)->with("timezone_list",$timezone_list);
   }

    public function savebasicsetting(Request $request)
    {
        $setting=Setting::find(1);
         $setting->title = $request->get("title");
        $setting->email = $request->get("email");
        $setting->phone = $request->get("phone");
        $setting->address = $request->get("address");
        $setting->currency = $request->get("currency");
        $setting->txt_charge = $request->get("txt_charge");
        $setting->timezone = $request->get("timezone");
        $setting->is_rtl = $request->get("is_rtl")?'1':'0';
        $logo = $setting->logo;
        $favicon = $setting->favicon;
        if($request->file("logo_image"))
        {            
            $file = $request->file('logo_image');
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension() ?: 'png';
            $folderName = '/img';
            $picture = time().rand() . '.' . $extension;
            $destinationPath = public_path() . $folderName;
            $request->file('logo_image')->move($destinationPath, $picture);
            $setting->logo = $picture; 
            $img_url = asset('public/img').'/'.$logo;
            if(file_exists($img_url)){
                unlink($img_url);
            }
        }
        if($request->file("favicon_image"))
        {
            $file = $request->file('favicon_image');
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension() ?: 'png';
            $folderName = '/img';
            $picture = time().rand() . '.' . $extension;
            $destinationPath = public_path() . $folderName;
            $request->file('favicon_image')->move($destinationPath, $picture);
            $setting->favicon = $picture;
            $img_url = asset('public/img').'/'.$favicon;
            if(file_exists($img_url)){
                unlink($img_url);
            }
        }
        $setting->save();
        Session::flash('message',__('message.Basic Information Save Successfully')); 
        Session::flash('alert-class', 'alert-success');
        return redirect('setting/2');
   }


    public function server_key(Request $request)
    {
        $setting=Setting::find(1);
        $setting->android_server_key = $request->get("android_server_key");
        $setting->ios_server_key = $request->get("ios_server_key");
        $setting->save();
        // Session::flash('message',"Server Keys Save Successfully");
        Session::flash('message',__('message.Server Keys Save Successfully'));
        Session::flash('alert-class', 'alert-success');
        return redirect('setting/4');
    }

    public function change_payment_detail(Request $request){        
        if($request->get("payment_method")=="Braintree"){
            PaymentGateway::where("payment_gateway_name","Braintree")->where("key_name","is_active")->update(["meta_value"=>$request->get("status")]);
            PaymentGateway::where("payment_gateway_name","Braintree")->where("key_name","environment")->update(["meta_value"=>$request->get("environment")]);
            PaymentGateway::where("payment_gateway_name","Braintree")->where("key_name","merchantId")->update(["meta_value"=>$request->get("merchantId")]);
            PaymentGateway::where("payment_gateway_name","Braintree")->where("key_name","publicKey")->update(["meta_value"=>$request->get("publicKey")]);
            PaymentGateway::where("payment_gateway_name","Braintree")->where("key_name","privateKey")->update(["meta_value"=>$request->get("privateKey")]);
            PaymentGateway::where("payment_gateway_name","Braintree")->where("key_name","TokenizationKeys")->update(["meta_value"=>$request->get("TokenizationKeys")]);

            $msg = __('message.Braintree Payment Details Save Successfully');

        }
        if($request->get("payment_method")=="Stripe"){
             PaymentGateway::where("payment_gateway_name","Stripe")->where("key_name","is_active")->update(["meta_value"=>$request->get("status")]);
            PaymentGateway::where("payment_gateway_name","Stripe")->where("key_name","public_key")->update(["meta_value"=>$request->get("public_key")]);
            PaymentGateway::where("payment_gateway_name","Stripe")->where("key_name","secert_key")->update(["meta_value"=>$request->get("secert_key")]);
            PaymentGateway::where("payment_gateway_name","Stripe")->where("key_name","currency")->update(["meta_value"=>$request->get("currency")]);

            $msg = __('message.Stripe Payment Details Save Successfully');

        }
        Session::flash('message',$msg);
        Session::flash('alert-class', 'alert-success');
        return redirect('setting/3');
    }

    public function show_contactus(){
        return view("admin.contact");
    }

    public function show_update_website_details(Request $request){
       
        $setting=Setting::find(1);
        $setting->appstore_url = $request->get("appstore_url");
        $setting->playstore_url = $request->get("playstore_url");
        $setting->largest_phlebotomist = $request->get("largest_phlebotomist");
        $setting->satisfied_customers = $request->get("satisfied_customers");
        $setting->total_test = $request->get("total_test");
        $setting->presence_cities = $request->get("presence_cities");
        $footer_logo = $setting->footer_logo;
        $main_banner = $setting->main_banner;
        $search_banner = $setting->search_banner;
        $mobile_app_banner = $setting->mobile_app_banner;
        if($request->file("footer_logo"))
        {
            $file = $request->file('footer_logo');
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension() ?: 'png';
            $folderName = '/img';
            $picture = time().rand() . '.' . $extension;
            $destinationPath = public_path() . $folderName;
            $request->file('footer_logo')->move($destinationPath, $picture);
            $setting->footer_logo = $picture;
            $img_url = asset('public/img').'/'.$footer_logo;
            if(file_exists($img_url)){
                unlink($img_url);
            }
        }
        if($request->file("main_banner"))
        {
            $file = $request->file('main_banner');
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension() ?: 'png';
            $folderName = '/img';
            $picture = time().rand() . '.' . $extension;
            $destinationPath = public_path() . $folderName;
            $request->file('main_banner')->move($destinationPath, $picture);
            $setting->main_banner = $picture;
            $img_url = asset('public/img').'/'.$main_banner;
            if(file_exists($img_url)){
                unlink($img_url);
            }
        }
        if($request->file("search_banner"))
        {
            $file = $request->file('search_banner');
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension() ?: 'png';
            $folderName = '/img';
            $picture = time().rand() . '.' . $extension;
            $destinationPath = public_path() . $folderName;
            $request->file('search_banner')->move($destinationPath, $picture);
            $setting->search_banner = $picture;
            $img_url = asset('public/img').'/'.$search_banner;
            if(file_exists($img_url)){
                unlink($img_url);
            }
        }

        if($request->file("mobile_app_banner"))
        {
            $file = $request->file('mobile_app_banner');
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension() ?: 'png';
            $folderName = '/img';
            $picture = time().rand() . '.' . $extension;
            $destinationPath = public_path() . $folderName;
            $request->file('mobile_app_banner')->move($destinationPath, $picture);
            $setting->mobile_app_banner = $picture;
            $img_url = asset('public/img').'/'.$mobile_app_banner;
            if(file_exists($img_url)){
                unlink($img_url);
            }
        }
        $setting->save();
     
        Session::flash('message',__('message.Website Info Save Successfully'));
        Session::flash('alert-class', 'alert-success');
        return redirect('setting/4');
    }

    public function contact_datatable(){
         $contact = Contactus::all();
         return DataTables::of($contact)
            ->editColumn('id', function ($contact) {
                return $contact->id;
            })
            ->editColumn('name', function ($contact) {
                return $contact->name;
            }) 
            ->editColumn('email', function ($contact) {
                return $contact->email;
            }) 
            ->editColumn('phone', function ($contact) {
                return $contact->phone;
            }) 
            ->editColumn('subject', function ($contact) {
                return $contact->subject;
            }) 
            ->editColumn('message', function ($contact) {
                return $contact->message;
            })     
            ->editColumn('action', function ($contact) {
                
                $deletetext = __('message.Delete');
                $delete = url('deletecontact',array('id'=>$contact->id));
                return '<a  href="https://mail.google.com/mail/?view=cm&fs=1&to='.$contact->email.'&su='.$contact->subject.'&body='.$contact->message.'" rel="tooltip"  target="blank" class="m-b-10 m-l-5" data-original-title="Remove"><i class="fa fa-envelope f-s-25" style="margin-right: 10px;font-size: x-large;color:black"></i></a><a onclick="delete_record(' . "'" . $delete. "'" . ')" rel="tooltip"  class="btn btn-danger" data-original-title="Remove" style="margin-right: 10px;color:white !important">'.$deletetext.'</a>';              
            })           
            ->make(true);
    }

    public function deletecontact($id){
        $store = Contactus::where("id",$id)->delete();
        // Session::flash('message',"Contact Delete Successfully");
        Session::flash('message',__('message.Contact Delete Successfully')); 
        Session::flash('alert-class', 'alert-success');
        return redirect()->back();
    }

    public function show_news(){
        $data=News::first();
        return view("admin.news",compact('data'));
    }

    public function sendnews(Request $request){
          $msg=$request->get("news");
          
          $setting=Setting::find(1);
          $getall = News::where('id',$request->get('id'))->update(["email"=>$request->get('news')]);
          $getall=News::all();
          foreach($getall as $g){
              $data=array();
              $data['email']=$g->email;
              $data['msg']=$msg;
              try {
                      $result=Mail::send('email.news', ['user' => $data], function($message) use ($data){
                         $message->to($data['email'],'customer')->subject(__('message.site_name'));
                      });
            
               } catch (\Exception $e) {
              }        
          }
       Session::flash('message',__('message.News Send Successfully'));
       Session::flash('alert-class', 'alert-success');
       return redirect()->back();
    }


}
