<?php

namespace App\Http\Controllers;

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

class SegmentationController extends Controller
{
    /**
    * Retrun index view
    */
    public function index(): View
    {
        Helper::checkPermissions('segmentation_list'); // check user permission
        $page = 'lists_segmentations';
        $page_title = __('app.segmentation_list');
        $breadcrumbs = [
            __('app.segmentation_list') => route('lists.index'),
            __('app.manage') => '#'
        ];
        return view('segmentations.lists.index',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
    * Retrun JSON datatable data
    */
    public function getSegmentations(Request $request): Void
    {
        $result = Segmentation::select('id', 'name', 'action', 'total', 'processed', 'action_list_id', 'created_at')
          ->app();

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

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

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

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

        foreach($segmentations as $segment) {
          $checkbox = "<input class=\"form-check-input\" type=\"checkbox\" value=\"{$segment->id}\">";
          $actions = '<div class="btn-group">';
          $actions .= '<button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">'.__('app.actions').'</button>';
          $actions .= '<ul class="dropdown-menu" style="">';
          $actions.= '<li><a class="dropdown-item" href="'.route('list_segmentations.edit', [$segment->id]).'"><i class="bi bi-pencil-square"></i> '.__('app.edit').'</a></li>';

          if($segment->action != 'Keep Copying' && $segment->action != 'Keep Moving') {
            $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('segment.action', ['id' => $segment->id, 'action' => 'Move']).'\')"><i class="bi bi-arrows"></i> '.__('app.move').'</a></li>';
            $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('segment.action', ['id' => $segment->id, 'action' => 'Keep Moving']).'\')"><i class="bi bi-arrows"></i> '.__('app.keep_moving').'</a></li>';

            $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('segment.action', ['id' => $segment->id, 'action' => 'Copy']).'\')"><i class="bi bi-copy"></i> '.__('app.copy').'</a></li>';
            $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('segment.action', ['id' => $segment->id, 'action' => 'Keep Copying']).'\')"><i class="bi bi-copy"></i> '.__('app.keep_copying').'</a></li>';
            $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="segmentExport(\''.route('segment.update.action', ['id' => $segment->id]).'\')"><i class="bi bi-upload"></i> '.__('app.export').'</a></li>';
          } else {
            $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="segmentStop(\''.route('segment.update.action', ['id' => $segment->id]).'\')"><i class="bi bi-stop-circle"></i> '.__('app.stop_segment').'</a></li>';
          }
          $actions .= '<li><a class="dropdown-item text-danger" href="javascript:;" onclick="destroy(\''.$segment->id.'\', \''.route('list_segmentations.destroy', [$segment->id]).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';
          $actions .= '</ul></div>';

          $progress = "( {$segment->processed} / {$segment->total} ) " . Helper::getPercentage($segment->processed, $segment->total);

          if($segment->action != 'Export') {
            $list_name = Lists::whereId($segment->action_list_id)->value('name'); 
            $action = empty($segment->action) ? '---' : $segment->action . ' <small><a class="link-info" href="javascript:;" onclick="viewModal(\'modal\', \''.route('lists.show', [$segment->action_list_id]).'\')">('.$list_name.')</a></small>' . " $progress";
          } else {
            $action = empty($segment->action) ? '---' : $segment->action . " $progress";
          }
          
          $data['data'][] = [
            "DT_RowId" => "row_{$segment->id}",
            $checkbox,
            $segment->name,
            $segment->total,
            $action,
            Helper::datetimeDisplay($segment->created_at),
            $actions
          ];
        }
        echo json_encode($data);
    }

    /**
    * Get cutom fields without dates or only dates
    */
    private function _customFields($without_dates = '!='): Object
    {
        $custom_fields = \App\Models\CustomField::select('id', 'name')
            ->whereAppId(\Auth::user()->app_id)
            ->where('type', $without_dates, 'date')
            ->get();
        return $custom_fields;
    }

    /**
    * Retrun create view
    */
    public function create(): View
    {
        Helper::checkPermissions('segmentation_list'); // check user permission
        $page = 'lists_segmentations';
        $page_title = __('app.segmentation_list');
        $breadcrumbs = [
            __('app.segmentation_list') => route('lists.index'),
            __('app.manage') => '#'
        ];
        $custom_fields = $this->_customFields();
        $custom_fields_date = $this->_customFields('=');
        return view('segmentations.lists.create')->with(compact('page', 'page_title', 'breadcrumbs', 'custom_fields', 'custom_fields_date'));
    }

    /**
    * Save data
    */
    public function store(Request $request): RedirectResponse
    {
        $data = $this->_segmentationData($request);
        $data['type'] = 'List';
        $segmentation = Segmentation::create($data);
        activity('create')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.segmentation') . " ({$request->name}) ". __('app.log_create'));

        return redirect()->route('list_segmentations.edit', $segmentation->id)
            ->with('success', ($request->name . ' ' . __('app.created_successfully')));
    }

    /**
    * Retrun edit view
    */
    public function edit($id)
    {
        Helper::checkPermissions('segmentation_list'); // check user permission
        $page = 'lists_segmentations';
        $page_title = __('app.segmentation_list');
        $breadcrumbs = [
            __('app.segmentation_list') => route('lists.index'),
            __('app.manage') => '#'
        ];
        $segment = Segmentation::whereId($id)->app()->first();

        $custom_fields = $this->_customFields();
        $custom_fields_date = $this->_customFields('=');
        return view('segmentations.lists.edit')->with(compact('page', 'page_title', 'breadcrumbs', 'segment', 'custom_fields', 'custom_fields_date'));
    }

    /**
    * Update data
    */
    public function update(Request $request, $id)
    {
        $data = $this->_segmentationData($request);
        $segment = Segmentation::findOrFail($id);
        $segment->fill($data)->save();

        activity('update')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.segmentation') . " ({$request->name}) ". __('app.log_update'));
        return redirect()->route('list_segmentations.edit', $id)
            ->with('success', ($request->name . ' ' . __('app.updated_successfully')));
    }


    /**
    * Retrun data for store or update
    */
    public function _segmentationData($request) {
        if($request->method() == 'POST') {
          $request->validate([
            'name' => 'required|unique:segmentations|string|max:255',
          ]);
        } else {
          $request->validate([
            'name' => 'required|string|max:255',
          ]);
        }

        $request->validate([
          'list_ids' => 'required',
        ]);
        $input = $request->except('_token');
        $input['attributes'] = json_encode($input);
        $input['user_id'] = Auth::user()->id;
        $input['app_id'] = Auth::user()->app_id;
        return $input;
    }

    /**
    * Delete one or more
    */
    public function destroy(int $id, Request $request): JsonResponse
    {
        if(!empty($request->action)) {
            $ids = array_values($request->ids);
            $names = json_encode(array_values(Segmentation::whereIn('id', $ids)->pluck('name')->toArray()));
            $destroy = Segmentation::whereIn('id', $ids)->delete();
        } else {
            $names = Segmentation::whereId($id)->value('name');
            $destroy = Segmentation::destroy($id);
        }
        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.segmentation') . " ({$names}) ". __('app.log_delete'));

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

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

    /**
    * Set to Copy / Move action
    */
    public function action(Request $request, $id, $action=null)
    {
        Helper::checkPermissions('lists_segmentations'); // check user permission
        if($request->method() == 'PUT') {
          $data['action_list_id'] = !empty($request->list_ids) ? $request->list_ids[0] : NULL;

          $data['action'] = $request->action ?? null;
          $data['processed'] = 0;
          $data['is_running'] = 0;
          $segment = Segmentation::findOrFail($id);
          $segment->fill($data)->save();

          if($data['action'] == 'Copy' || $data['action'] == 'Keep Copying') {
            activity($data['action'])->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.segment') . " ({$segment->name}) ". __('app.log_segment_copy'));
            echo __('app.msg_copy_segment');
          } elseif($data['action'] == 'Move' || $data['action'] == 'Keep Moving') {
            activity($data['action'])->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.segment') . " ({$segment->name}) ". __('app.log_segment_move'));
            echo __('app.msg_move_segment');
          } elseif($data['action'] == 'Export') {
            activity($data['action'])->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.segment') . " ({$segment->name}) ". __('app.log_export'));
            echo __('app.msg_export_segment');
          }
        } elseif($request->method() == 'GET') {
          return view('segmentations.lists.copy_move')->with(compact('id', 'action'));
        }
    }
}
