<?php

namespace App\Http\Controllers;

use App\Helpers\Helpers;
use App\Models\Device;
use App\Models\Template;
use Illuminate\Http\Request;

class TemplateController extends Controller
{
    public function list()
    {
        $user = auth()->user();
        $devices = Device::where('user_id', '=', $user->id)->where('status', '=', 'ONLINE')->get();
        $phonebooks = $user->phonebooks;
        $templates = $user->templates;
        $globals = [];
        $gUserIds = empty(Helpers::setting('globalUserIds')) ? null : json_decode('['.Helpers::setting('globalUserIds').']');
        if($gUserIds && Helpers::isEx() && $user->package->global_senders) {
          foreach($gUserIds as $gUserId) {
            if ($gUserId == $user->id) continue;
            $gDevices = Device::where('user_id', $gUserId)->get();
            if (empty($gDevices)) continue;
            foreach($gDevices as $gDevice) {
              if ($gDevice->status !== 'ONLINE') continue;
              array_push($globals, ['user_id' => $gUserId, 'name' => $gDevice->name, 'sender' => $gDevice->sender]);
            }
          }
        }
        // dd($globals);
        return view('/template-list', compact('templates', 'devices', 'phonebooks', 'globals'));
    }

    public function store(Request $request)
    {
        $request->validate(['mediafile' => 'nullable|file|mimes:xml,jpeg,png,jpg,gif,pdf,xls,xlsx,ppt,pptx,doc,docx,csv,mp3,ogg,mp4']); // |max:20480
        $user = auth()->user();
        $user_id = $user->id;
        if (!empty($request->mediafile)) {
            //$media_ext = $request->mediafile->getClientOriginalExtension();
            $file = Helpers::normalize($request->mediafile->getClientOriginalName());
            $mediafile = pathinfo($file, PATHINFO_FILENAME) . '-' . rand(111111, 999999) . '.' . pathinfo($file, PATHINFO_EXTENSION);
            $mediaurl = url("/users/{$user_id}/template/{$mediafile}");
            $media_upload = $request->mediafile->move(public_path("users/{$user_id}/template"), $mediafile);
        } else {
            // $mediafile = '';
            $mediaurl = '';
        }
        $template = new Template();
        $template->user_id = $user->id;
        $template->name = $request->input('name');
        if (Template::where('user_id', '=', $user->id)->where('name', '=', $template->name)->count() > 0) {
            return redirect()->back()->with(['danger_alert' => __('Duplicate found. Failed to add') . ': ' . $template->name]);
        }
        $template->msgtext = $request->input('msgtext');
        // $template->mediafile = $mediafile;
        $template->mediaurl = $mediaurl;
        $template->save();
        return redirect()->back()->with(['success_alert' => __('Successfully add') . ': ' . $template->name]);
    }

    public function update(Request $request, Template $template)
    {
        $request->validate(['mediafile' => 'nullable|file|mimes:xml,jpeg,png,jpg,gif,pdf,xls,xlsx,ppt,pptx,doc,docx,mp3,ogg,mp4']);
        $user_id = auth()->user()->id;
        if (!empty($request->mediafile)) {
            if (!empty($request->input('prev_mediafile')) && file_exists(public_path("users/{$user_id}/template/{$request->input('prev_mediafile')}"))) {
              unlink(public_path("users/{$user_id}/template/{$request->input('prev_mediafile')}"));
            }
            //$media_ext = $request->mediafile->getClientOriginalExtension();
            $file = Helpers::normalize($request->mediafile->getClientOriginalName());
            $mediafile = pathinfo($file, PATHINFO_FILENAME) . '-' . rand(111111, 999999) . '.' . pathinfo($file, PATHINFO_EXTENSION);
            $mediaurl = url("/users/{$user_id}/template/{$mediafile}");
            $media_upload = $request->mediafile->move(public_path("users/{$user_id}/template"), $mediafile);
        } else {
            // $mediafile = $request->input('prev_mediafile');
            $mediaurl = $request->input('prev_mediaurl');
        }
        $template = Template::where('id', '=', $request->input('template_id'))->first();
        if (auth()->user()->id != $template->user_id && auth()->user()->role !== 'admin') return redirect()->back()->with(['danger_alert' => __('You are not allowed to update Template')]);
        $template->name = $request->input('name');
        $template->msgtext = $request->input('msgtext');
        // $template->mediafile = $mediafile;
        $template->mediaurl = $mediaurl;
        $template->save();
        return redirect()->back()->with(['success_alert' => __('Successfully update Template') . ': ' . $template->name]);
    }

    public static function recurring()
    {
        // $templates = Template::where('schedule', '<>', null)
    }

    public function destroy(Request $request)
    {
        $template = Template::where('id', '=', $request->template_id)->first();
        if (auth()->user()->id != $template->user_id && auth()->user()->role !== 'admin') return redirect()->back()->with(['danger_alert' => __('You are not allowed to delete Template')]);
        if (!empty($template->mediaurl)) {
            $arrMediaurl = (explode('/', $template->mediaurl));
            $mediafile = end($arrMediaurl);
            if (file_exists(public_path("users/{$template->user_id}/template/{$mediafile}"))) {
              unlink(public_path("users/{$template->user_id}/template/{$mediafile}"));
            }
        }
        $template->delete();
        return redirect()->back()->with(['success_alert' => __('Successfully delete Template')]);
    }
}
