<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use App\Models\Template;
use App\Http\Helper\Helper;
use Auth;

class TemplateController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        Helper::checkPermissions('templates');
        $page = 'campaigns_templates';        
        $breadcrumbs = [
            __('app.templates') => route('templates.index')
        ];

        $page_title = __('app.templates');
        return view('templates.index',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
   * Retrun JSON datatable data
  */
  public function getTemplates(Request $request)
  {
    $result = Template::select('id', 'name', 'created_at')
      ->whereAppId(Auth::user()->app_id);

    $columns = ['id', 'id', 'name', 'created_at'];

    $data = Helper::dataFilters($request, $result, $columns);

    $result = $data['result'];
    $templates = $result->get();

    $data =  Helper::datatableTotals($data['total']);

    foreach($templates as $template) {
      $checkbox = "<input class=\"form-check-input\" type=\"checkbox\" value=\"{$template->id}\">";
      $actions = '<div class="btn-group">
        <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">'.__('app.actions').' <span class="caret"></span></button><ul class="dropdown-menu" role="menu">';
      $actions .= '<li><a class="dropdown-item" target="_blank" href="'.route('templates.show', [$template->id]).'"><i class=" bi bi-eye"></i> '.__('app.view').'</a></li>';
      $actions .= '<li><a class="dropdown-item" href="'.route('templates.edit', [$template->id]).'"><i class="bi bi-pencil-square"></i> '.__('app.edit').'</a></li>';
      $actions .= '<li><a class="dropdown-item" href="'.route('broadcasts.create', ['tid' => base64_encode($template->id)]).'"><i class="bi bi-clipboard-data"></i> '.__('app.make_campaign').'</a></li>';
      $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('send.email', [0, 0, $template->id]).'\')"><i class="bi bi-send"></i> '.__('app.send_test_email').'</a></li>';
      $actions .= '<li><a class="dropdown-item text-danger" href="javascript:;" onclick="destroy(\''.$template->id.'\', \''.route('templates.destroy', [$template->id]).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';
      $actions .= '</ul>
        </div>';
      $data['data'][] = [
        "DT_RowId" => "row_{$template->id}",
        $checkbox,
        $template->id,
        '<a class="link-info" target="_blank" href="'.route('templates.show', [$template->id]).'">'.$template->name.'</a>',
        Helper::datetimeDisplay($template->created_at),
        $actions
      ];
    }
    echo json_encode($data);
  }

  /**
     * Show the form for creating a new resource.
     */
    public function templateSelect(Request $request): View
    {
        Helper::checkPermissions('templates');
        return view('templates.select');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request): View
    {
        Helper::checkPermissions('templates');
        $action = 'create';
        $id = 0;
        $page = 'campaigns_templates';
        $page_title = __('app.templates');

        $editor = $request->input('editor');
        if($editor == 2)    
            return view('templates.rz_builder.index')->with(compact('id', 'action', 'page', 'page_title'));
        else
            return view('templates.builder.index')->with(compact('id', 'action', 'page', 'page_title'));

    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
          'name' => 'required',
        ]);
        $input = $request->all();
        //print_r($input);
        $sanitizer = new \Phlib\XssSanitizer\Sanitizer();
        $input['content'] = !empty($input['content']) ? Helper::XSSReplaceTags($sanitizer->sanitize($input['content'])) : null;
        if($input['action'] == 'create') {
           $input['user_id'] = Auth::user()->id;
           $input['app_id'] = Auth::user()->app_id;
           $input['type'] = $input['type'];
           $template = Template::create($input);
           activity('create')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.template') . " ({$request->name}) ". __('app.log_create')); // log
           return $template->id;
        } elseif($input['action'] == 'edit') {
          $template = Template::findOrFail($input['id']);
          $input['user_id'] = Auth::user()->id;
          $input['app_id'] = Auth::user()->app_id;
          $template->fill($input)->save();
          activity('update')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.template') . " ({$request->name}) ". __('app.log_update')); // log
          return $input['id'];
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\list  $list
     * @return \Illuminate\Http\Response
     */
    public function show(Template $template): View
    {   
        Helper::checkPermissions('templates');
        $content_html = $template->content;
        return view('broadcasts.view')->with('content_html', $content_html);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Template $template): View
    {
        Helper::checkPermissions('templates');
        $action = 'edit';
        $page = 'campaigns_templates';
        $page_title = __('app.templates');
        $id = $template->id;

        if($template->type == 2)
            return view('templates.rz_builder.index')->with(compact('id', 'action', 'page', 'page_title'));
        else 
            return view('templates.builder.index')->with(compact('id', 'action', 'page', 'page_title'));
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $id, Request $request): JsonResponse
    {
        if(!empty($request->action)) {
            $ids = array_values($request->ids);
            $names = json_encode(array_values(Template::whereIn('id', $ids)->pluck('name')->toArray()));
            $destroy = Template::whereIn('id', $ids)->delete();
        } else {
            $names = Template::whereId($id)->value('name');
            $destroy = Template::destroy($id);
        }
        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.template') . " ({$names}) ". __('app.log_delete'));

        $data = [
          'success' => true,
          'message' => __('app.deleted_successfully')
        ];

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

    /**
    * Return drag & drop builder
    */
    function getBuilder(Request $request): View
    {
        Helper::checkPermissions('templates');
        $action = $request->input('action');
        $id = $request->input('id');
        if($id == 0) {
          $name = $html = '';
        } else {
          $template = Template::whereId($id)->app()->first();
          $name = $template->name;
          $html = Helper::XSSReplaceTags(Helper::decodeString($template->content));
        }
        return view('templates.builder.builder')->with(compact('id', 'action', 'name', 'html'));;
    }

    /**
    * Return MailCarry campaign builder for create or edit
    */
    function getRZBuilder(Request $request): View
    {
        Helper::checkPermissions('templates'); // check user permission
        $action = $request->input('action');
        $id = $request->input('id');
        if($id == 0) {
          $name = $html = '';
        } else {
          $template = Template::whereId($id)->app()->first();
          $name = $template->name;
          $html = Helper::extractHtmlTagContents('body', Helper::XSSReplaceTags(Helper::decodeString($template->content)));
        }
        return view('templates.rz_builder.builder')->with(compact('id', 'action', 'name', 'html'));
    }

    /**
   * Retrun HTML data of a template
  */
  public function getHTMLContent($id)
  {
    return Template::whereId($id)->app()->value('content');
  }
}
