<?php

namespace App\Http\Controllers\Backend\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Auth;
use App\Models\Blog;
use App\Models\Template;
use App\Models\User;
use App\Models\WhatsappApi;
use Illuminate\Support\Facades\Http;
use View;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use Alert;
use App\Imports\ReadAttachment;
use App\Models\Users\Broadcast;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\HeadingRowImport;

class BroadcastController extends Controller
{


   /**
    * Display a listing of the resource.
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {

      $broadcastes = Broadcast::select('broadcaste.*', 'templates.id as template_id', 'templates.template_name', 'templates.hader_format', 'templates.body_text')
         ->LEFTjoin('templates', 'templates.id', '=', 'broadcaste.template_id')
         ->where('broadcaste.account_id', '=',  $request->session()->get('account_id'))
         ->where('broadcaste.status', '>',  0)
         ->orderBy('broadcaste.created_at', 'desc')
         ->get();
      $data['broadcastes'] = $broadcastes;

      return view('backend.user.broadcast.index', $data);
   }

   public function submitForm(Request $request)
   {


      $csv_orignal_name = $request->file('csv_file')->getClientOriginalName();
      $csv_file_name = $request->session()->get('account_id') . '-' . time() . '-' . $request->file('csv_file')->getClientOriginalName();
      $csv_file_path = 'storage/app/' . $request->file('csv_file')->storeAs('docs/attachments', $csv_file_name);

      if ($request->file('media_document')) {
         $document_orignal_name = $request->file('media_document')->getClientOriginalName();
         $document_file_name = $request->session()->get('account_id') . '-' . time() . '-' . $request->file('media_document')->getClientOriginalName();
         $document_file_path = 'storage/app/' . $request->file('media_document')->storeAs('docs/header_attachments', $document_file_name);
      }
      if ($request->file('media_image')) {
         $document_orignal_name = $request->file('media_image')->getClientOriginalName();
         $document_file_name = $request->session()->get('account_id') . '-' . time() . '-' . $request->file('media_image')->getClientOriginalName();
         $document_file_path = 'storage/app/' . $request->file('media_image')->storeAs('docs/header_attachments', $document_file_name);
      }
      $data = $request->all();
      $date = $data['date'];
      $time = $data['time'];
      $submit_data = array(
         'broadcast_name' => $data['broadcast_name'],
         'template_id' => $data['live_search'],
         'csv_name' => $csv_orignal_name,
         'csv_path' => $csv_file_path,
         'media_name' => $document_orignal_name ?? '',
         'media_path' => $document_file_path ?? '',
         'time_to_execuate' => date('Y-m-d H:i:s', strtotime("$date $time")),
         'status' => (int)$data['send'],
         'created_id' => auth()->user()->id,
         'account_id' => $request->session()->get('account_id')
      );

      $id = DB::table('broadcaste')->insertGetId($submit_data);
      if ($id) {
         //if schdule right now run the broadcast
         if ($data['send'] == 1) {

            // 1658553709-0params
            //1658559909-1params
            //1658552845-3params
            $tempalte_data = Template::find($data['live_search']);
            $csv_file_name = $csv_file_name;
            Broadcast::preProcess($csv_file_name, $tempalte_data, $id);
         }
         return redirect(url('user/broadcast/'))->with('status', 'Broadcast created!');;
      }
   }

   public function updateForm(Request $request)
   {
      $data = $request->all();
      $date = $data['date'];
      $time = $data['time'];
      $submit_data = array(
         'broadcast_name' => $data['broadcast_name'],
         'template_id' => $data['live_search'],
         'time_to_execuate' => date('Y-m-d H:i:s', strtotime("$date $time")),
         'status' => (int)$data['send'],
         'created_id' => auth()->user()->id,
         'account_id' => $request->session()->get('account_id')
      );
      if ($request->file('csv_file')) {
         $csv_orignal_name = $request->file('csv_file')->getClientOriginalName();
         $csv_file_name = $request->session()->get('account_id') . '-' . time() . '-' . $request->file('csv_file')->getClientOriginalName();
         $csv_file_path = 'storage/app/' . $request->file('csv_file')->storeAs('docs/attachments', $csv_file_name);
         $submit_data['csv_name'] = $csv_orignal_name;
         $submit_data['csv_path'] = $csv_file_path;
      }

      if ($request->file('media_document')) {
         $document_orignal_name = $request->file('media_document')->getClientOriginalName();
         $document_file_name = $request->session()->get('account_id') . time() . '-' . $request->file('media_document')->getClientOriginalName();
         $document_file_path = 'storage/app/' . $request->file('media_document')->storeAs('header_attachments', $document_file_name);
         $submit_data['media_name'] = $document_orignal_name;
         $submit_data['media_path'] = $document_file_path;
      }
      if ($request->file('media_image')) {
         $document_orignal_name = $request->file('media_image')->getClientOriginalName();
         $document_file_name = $request->session()->get('account_id') . '-' . time() . '-' . $request->file('media_image')->getClientOriginalName();
         $document_file_path = 'storage/app/' . $request->file('media_image')->storeAs('header_attachments', $document_file_name);
         $submit_data['media_name'] = $document_orignal_name;
         $submit_data['media_path'] = $document_file_path;
      }

      $affected = DB::table('broadcaste')
         ->where('id', $data['id'])
         ->update($submit_data);
      if ($affected) {
         return redirect(url('user/broadcast/'))->with('status', 'Broadcast updated!');
      }
      return redirect(url('user/broadcast/updateBroadCast/' . $data['id']))->with('status', 'Nothing updated!');
   }
   public function createBroadCast()
   {
      return view('backend.user.broadcast.createBroadCast');
   }
   public function updateBroadCast($id)
   {
      $broadcaste = DB::select('SELECT broadcaste.*, templates.id as template_id, templates.template_name, templates.hader_format,templates.body_text 
      FROM broadcaste LEFT JOIN templates ON templates.id=broadcaste.template_id WHERE broadcaste.id =' . $id);


      $data['broadcaste'] = $broadcaste[0];
      return view('backend.user.broadcast.updateBroadCast', $data);
   }

   public function deleteBroadcast(Request $request)
   {
      $broadcaste = DB::table('broadcaste')
         ->where('id', $request->all()['id'])
         ->get()
         ->first();
      if ($broadcaste->csv_path) {
         $csv_path = substr($broadcaste->csv_path, 7);
         unlink(storage_path($csv_path));
      }
      if ($broadcaste->media_path) {
         $media_path = substr($broadcaste->csv_path, 7);
         unlink(storage_path($media_path));
      }
      $affected = DB::table('broadcaste')
         ->where('id', $request->all()['id'])
         ->update(['status' => 0]);
      return $affected;
   }
   public function checkUniqueBroadcast(Request $request)
   {
      $data = DB::table('broadcaste')
         ->where('broadcast_name', '=', $request->all()['value'])
         ->where('status', '>', 0)
         ->where('account_id', '=', $request->session()->get('account_id'))
         ->get();
      return $data;
   }
   public function getAll(Request $request)
   {

      if ($request->ajax()) {
         $can_edit = $can_delete = '';
         if (!auth()->user()->can('blog-edit')) {
            $can_edit = "style='display:none;'";
         }
         if (!auth()->user()->can('blog-delete')) {
            $can_delete = "style='display:none;'";
         }

         $blog = Blog::orderby('created_at', 'desc')->get();
         return Datatables::of($blog)
            ->addColumn('file_path', function ($blog) {
               return "<img src='" . asset($blog->file_path) . "' width='60px'>";
            })
            ->addColumn('title', function ($blog) {
               return Str::words($blog->title, 10, '...');
            })
            ->addColumn('status', function ($blog) {
               return $blog->status ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-danger">Inactive</span>';
            })
            ->addColumn('action', function ($blog) use ($can_edit, $can_delete) {
               $html = '<div class="btn-group">';
               $html .= '<a data-toggle="tooltip" ' . $can_edit . '  id="' . $blog->id . '" class="btn btn-xs btn-info mr-1 edit" title="Edit"><i class="fa fa-edit"></i> </a>';
               $html .= '<a data-toggle="tooltip" ' . $can_delete . ' id="' . $blog->id . '" class="btn btn-xs btn-danger delete" title="Delete"><i class="fa fa-trash"></i> </a>';
               $html .= '</div>';
               return $html;
            })
            ->rawColumns(['action', 'status', 'file_path'])
            ->addIndexColumn()
            ->make(true);
      } else {
         return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      }
   }

   public function allRoless(Request $request)
   {
   }

   /**
    * Show the form for creating a new resource.
    * @return \Illuminate\Http\Response
    */
   public function create(Request $request)
   {



      if ($request->ajax()) {
         //$haspermision = auth()->user()->can('notice-create');
         // if ($haspermision) {
         $view = View::make('backend.user.broadcast.create')->render();
         return response()->json(['html' => $view]);
         //} else {
         abort(403, 'Sorry, you are not authorized to access the page');
         //}
      } else {
         return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      }
   }

   /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request $request
    *
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
      if ($request->ajax()) {
         $haspermision = auth()->user()->can('blog-create');
         if ($haspermision) {

            $rules = [
               'title' => 'required',
               'photo' => 'max:2048|dimensions:max_width=2000,max_height=1000', // 2mb
            ];

            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
               return response()->json([
                  'type' => 'error',
                  'errors' => $validator->getMessageBag()->toArray()
               ]);
            } else {

               $upload_ok = 1;
               $file_path = 'assets/images/blog/default.png';

               if ($request->hasFile('photo')) {
                  $extension = strtolower($request->file('photo')->getClientOriginalExtension());
                  if ($extension == "jpg" || $extension == "jpeg" || $extension == "png") {
                     if ($request->file('photo')->isValid()) {
                        $destinationPath = public_path('assets/images/blog'); // upload path
                        $extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
                        $fileName = time() . '.' . $extension; // renameing image
                        $file_path = 'assets/images/blog/' . $fileName;
                        $request->file('photo')->move($destinationPath, $fileName); // uploading file to given path
                        $upload_ok = 1;
                     } else {
                        return response()->json([
                           'type' => 'error',
                           'message' => "<div class='alert alert-warning'>File is not valid</div>"
                        ]);
                     }
                  } else {
                     return response()->json([
                        'type' => 'error',
                        'message' => "<div class='alert alert-warning'>Error! File type is not valid</div>"
                     ]);
                  }
               }

               if ($upload_ok == 0) {
                  return response()->json([
                     'type' => 'error',
                     'message' => "<div class='alert alert-warning'>Sorry Failed</div>"
                  ]);
               } else {
                  $blog = new Blog;
                  $blog->title = $request->input('title');
                  $blog->description = $request->input('description');
                  $blog->category = $request->input('category');
                  $blog->uploaded_by = auth()->user()->id;
                  $blog->file_path = $file_path;
                  $blog->save(); //
                  return response()->json(['type' => 'success', 'message' => "Successfully Created"]);
               }
            }
         } else {
            abort(403, 'Sorry, you are not authorized to access the page');
         }
      } else {
         return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      }
   }

   // Update templates from Whatsapp manager
   public function uploadtemplates(Request $request)
   {


      $obj = new WhatsappApi();
      $resp =  $obj->getContent("message_templates");



      // if session of account not exist return back
      if ($request->session()->has('account_id')) {
         $account_id =  $request->session()->get('account_id');
      } else {
         return  'No data in the session';
      }

      // first we need to clean the previous tempalte data
      Template::delTemplates();
      $user_data = Auth::user();

      $decoded_json = json_decode($resp, true);
      $templates = $decoded_json['data'];


      foreach ($templates as $temp) {
         $id = $temp['id'];
         $name = $temp['name'];
         $language = $temp['language'];
         $status = $temp['status'];
         $components = $temp['components'];

         foreach ($components as $comp) {
            $comp_obj = (object)$comp;

            if (in_array('HEADER', $comp)) {

               if (in_array('TEXT', $comp)) {
                  $header_text = $comp_obj->text;
                  $header_format = "TEXT";
               }
               if (in_array('DOCUMENT', $comp)) {

                  $header_text = 'DOCUMENT';
                  $header_format = "DOCUMENT";
               }
               if (in_array('VIDEO', $comp)) {

                  $header_text = 'VIDEO';
                  $header_format = 'VIDEO';
               }
               if (in_array('IMAGE', $comp)) {

                  $header_text = 'IMAGE';
                  $header_format = 'IMAGE';
               }
            } else {
               $header_text = '';
               $header_format = '';
            }
            // NOW GET BODY
            if (in_array('BODY', $comp)) { //
               $body_text = $comp_obj->text;
            }
            // NOW GET FOOTER
            if (in_array('FOOTER', $comp)) { //
               $footer_text = $comp_obj->text;
            } else {
               $footer_text = '';
            }

            // NOW GET Buttons
            if (in_array('BUTTONS', $comp)) { //
               // remove unneccessar button first array
               $comp_button = array_shift($comp);
               foreach ($comp as $button) {
                  //dd(json_encode($button));
                  foreach ($button as $btn) {
                     //dd($btn['text']);
                     if (in_array('QUICK_REPLY', $btn)) {

                        $button_type = $btn['type'];
                        $button_txt = json_encode($button);
                     } elseif (in_array('URL', $btn)) {
                        $button_type = $btn['type'];
                        $button_txt = json_encode($button);
                        $button_url = $btn['url'];
                     } else {
                        $button_type = '';
                        $button_txt = '';
                        $button_url = '';
                     }
                  }
               }

               //$footer_text = $comp_obj->text;
            } else {
               $button_type = '';
               $button_txt = '';
               $button_url = '';
            }
         }



         try {
            DB::table('templates')->insert(
               array(
                  'template_id' => $id,
                  'template_name' => $name,
                  'template_lang' => $language,
                  'template_text' => '',
                  'hader_format' => $header_format,
                  'hader_text' => $header_text,
                  'body_text' => $body_text,
                  'footer_text' => $footer_text,
                  'button_type' => $button_type,
                  'button_text' => $button_txt,
                  'button_url' => $button_url,
                  'status' => ($status == 'APPROVED') ? 1 : 0,
                  'created_id' => Auth::id(),
                  'created_at' => date("Y-m-d H:i:s"),
                  'user_id' => $user_data->company_id,
                  'accounts_id' => session('account_id')

               )
            );
         } catch (\Illuminate\Database\QueryException $ex) {
            dd($ex->getMessage());
         }
      }

      $broadcastes = Broadcast::select('broadcaste.*', 'templates.id as template_id', 'templates.template_name', 'templates.hader_format', 'templates.body_text')
         ->LEFTjoin('templates', 'templates.id', '=', 'broadcaste.template_id')
         ->where('broadcaste.account_id', '=',  $request->session()->get('account_id'))
         ->where('broadcaste.status', '>',  0)
         ->orderBy('broadcaste.created_at', 'desc')
         ->get();
      $data['broadcastes'] = $broadcastes;
      return view('backend.user.broadcast.index', $data);
   }


   /**
    * Show the form for editing the specified resource.
    *
    * @param  \App\Models\Blog $blog
    *
    * @return \Illuminate\Http\Response
    */
   public function edit(Request $request, Blog $blog)
   {
      if ($request->ajax()) {
         $haspermision = auth()->user()->can('notice-edit');
         if ($haspermision) {
            $view = View::make('backend.user.blog.edit', compact('blog'))->render();
            return response()->json(['html' => $view]);
         } else {
            abort(403, 'Sorry, you are not authorized to access the page');
         }
      } else {
         return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      }
   }

   /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request $request
    * @param  \App\Models\Blog $blog
    *
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, Blog $blog)
   {
      if ($request->ajax()) {
         $haspermision = auth()->user()->can('blog-edit');
         if ($haspermision) {

            $rules = [
               'title' => 'required',
               'photo' => 'max:2048|dimensions:max_width=2000,max_height=1000', // 2mb
            ];

            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
               return response()->json([
                  'type' => 'error',
                  'errors' => $validator->getMessageBag()->toArray()
               ]);
            } else {

               if ($request->hasFile('photo')) {
                  $extension = strtolower($request->file('photo')->getClientOriginalExtension());
                  if ($extension == "jpg" || $extension == "jpeg" || $extension == "png") {
                     if ($request->file('photo')->isValid()) {
                        $destinationPath = public_path('assets/images/blog'); // upload path
                        $extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
                        $fileName = time() . '.' . $extension; // renameing image
                        $file_path = 'assets/images/blog/' . $fileName;
                        $request->file('photo')->move($destinationPath, $fileName); // uploading file to given path
                        $upload_ok = 1;
                     } else {
                        return response()->json([
                           'type' => 'error',
                           'message' => "<div class='alert alert-warning'>File is not valid</div>"
                        ]);
                     }
                  } else {
                     return response()->json([
                        'type' => 'error',
                        'message' => "<div class='alert alert-warning'>Error! File type is not valid</div>"
                     ]);
                  }
               } else {
                  $upload_ok = 1;
                  $file_path = $request->input('SelectedFileName');
               }

               if ($upload_ok == 0) {
                  return response()->json([
                     'type' => 'error',
                     'message' => "<div class='alert alert-warning'>Sorry Failed</div>"
                  ]);
               } else {
                  $blog = Blog::findOrFail($blog->id);
                  $blog->title = $request->input('title');
                  $blog->description = $request->input('description');
                  $blog->category = $request->input('category');
                  $blog->uploaded_by = auth()->user()->id;
                  $blog->file_path = $file_path;
                  $blog->status = $request->input('status');
                  $blog->save(); //
                  return response()->json(['type' => 'success', 'message' => "Successfully Updated"]);
               }
            }
         } else {
            abort(403, 'Sorry, you are not authorized to access the page');
         }
      } else {
         return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      }
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param  \App\Models\Blog $blog
    *
    * @return \Illuminate\Http\Response
    */
   public function destroy(Request $request, Blog $blog)
   {
      if ($request->ajax()) {
         $haspermision = auth()->user()->can('notice-delete');
         if ($haspermision) {
            $blog->delete();
            return response()->json(['type' => 'success', 'message' => 'Successfully Deleted']);
         } else {
            abort(403, 'Sorry, you are not authorized to access the page');
         }
      } else {
         return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      }
   }

   /**
    * Display the specified resource.
    *
    * @param  \App\Models\Blog $blog
    *
    * @return \Illuminate\Http\Response
    */
   public function show(Request $request, Blog $blog)
   {

      if ($request->ajax()) {
         $user_data = Auth::user();
         if ($request->has('q')) {
            $search = $request->q;
            $template = Template::select("id", "template_name")
               ->where('template_name', 'LIKE', "%$search%")
               ->where('accounts_id', '=', $request->session()->get('account_id'))
               ->get();
         } else {
            $template = Template::select("id", "template_name")
               ->where('accounts_id', '=', $request->session()->get('account_id'))
               ->get();
         }
         return response()->json($template);
      }


      exit();
      // if ($request->ajax()) {
      //    $haspermision = auth()->user()->can('notice-view');
      //    if ($haspermision) {
      //       $view = View::make('backend.user.broadcast.view', compact('blog'))->render();
      //       return response()->json(['html' => $view]);
      //    } else {
      //       abort(403, 'Sorry, you are not authorized to access the page');
      //    }
      // } else {
      //    return response()->json(['status' => 'false', 'message' => "Access only ajax request"]);
      // }
   }
}
