<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\TriggerRequest;
use App\Models\Trigger;
use App\Models\DripScheduleStat;
use App\Http\Helper\Helper;
use Auth;

class TriggerController extends Controller
{
    /**
    * Retrun index view
    */
    public function index(): View
    {
        Helper::checkPermissions('schedule_triggers');
        $page = 'schedule_triggers';
        $page_title = __('app.triggers');
        $breadcrumbs = [
            __('app.schedule') => '#',
            __('app.triggers') => route('triggers.index'),
            __('app.manage') => '#'
        ];
        return view('triggers.index')->with(compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
    * Retrun JSON datatable data
    */
    public function getTriggers(Request $request): Void
    {
        $result = Trigger::app()
            ->with('triggerScheduleStat')
            ->with('dripSchedule');;

        $columns = ['id', 'name', 'execution_datetime', 'is_active', 'based_on', 'action', 'created_at'];

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

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

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

        foreach($triggers as $trigger) {
          $checkbox = "<input class=\"form-check-input\" type=\"checkbox\" value=\"{$trigger->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" href="'.route('triggers.edit', [$trigger->id]).'"><i class="bi bi-pencil-square"></i> '.__('app.edit').'</a></li>';
          
          /*$actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="restartTrigger(\''.$trigger->id.'\', \''.__('app.trigger_restart_msg').'\')"><i class="fa fa-refresh "></i>'.__('app.restart_trigger').'</a></li>';*/

          if($trigger->action == 'start_drip') {
            if(!empty($trigger->DripSchedule->id)) {
              $schedule_drip_stat = DripScheduleStat::whereDripScheduleId($trigger->DripSchedule->id)->first();
              $name = '<a class="link-info" href="javascript:;" onclick="viewModal(\'modal\', \''.route('detail.stat.drip', [$schedule_drip_stat->id, 'summary', 'analatics.drips.summary_popup']).'\')"> '.$trigger->name.'</a>';

              $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('detail.stat.drip', [$schedule_drip_stat->id, 'summary', 'analatics.drips.summary_popup']).'\')"><i class="bi bi-pie-chart"></i> '.__('app.summary').'</a></li>';
              $actions .= '<li><a class="dropdown-item" href="'.route('detail.stat.drip', ['id' =>  $schedule_drip_stat->id]).'" ><i class="bi bi-bar-chart"></i> '.__('app.stats').'</a></li>';
            } else {
              $name = $trigger->name;
            }
          } else {
            if(!empty($trigger->TriggerScheduleStat->id)) {
              $name = '<a class="link-info" href="javascript:;" onclick="viewModal(\'modal\', \''.route('detail.stat.trigger', [$trigger->TriggerScheduleStat->id, 'summary', 'analatics.triggers.summary_popup']).'\')">'.$trigger->name.'</a>';

              $actions .= '<li><a class="dropdown-item" href="javascript:;" onclick="viewModal(\'modal\', \''.route('detail.stat.trigger', [$trigger->TriggerScheduleStat->id, 'summary', 'analatics.triggers.summary_popup']).'\')"><i class="bi bi-pie-chart"></i> '.__('app.summary').'</a></li>';
              $actions .= '<li><a class="dropdown-item" href="'.route('detail.stat.trigger', ['id' => $trigger->TriggerScheduleStat->id]).'"><i class="bi bi-bar-chart"></i> '.__('app.stats').'</a></li>';
            } else {
              $name = $trigger->name;
            }
          }

          $actions .= '<li><a class="dropdown-item text-danger" href="javascript:;" onclick="destroy(\''.$trigger->id.'\', \''.route('triggers.destroy', [$trigger->id]).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';

          $actions .= '</ul></div>';

          $status = $trigger->is_active  
            ? "<span class='badge bg-success-gradient'>".__('app.yes')."</span>"
            : "<span class='badge bg-danger-gradient'>".__('app.no')."</span>";

          $data['data'][] = [
            "DT_RowId" => "row_{$trigger->id}",
            $checkbox,
            $name,
            ucwords($trigger->based_on),
            ucwords(str_replace('_', ' ', $trigger->action)),
            $status,
            Helper::datetimeDisplay($trigger->created_at),
            $actions
          ];
        }
        echo json_encode($data);
    }

    /**
    * Retrun create view
    */
    public function create(): View
    {
        Helper::checkPermissions('schedule_triggers'); // check user permission
        $page = 'schedule_triggers';
        $page_title = __('app.add_new_trigger');
        $breadcrumbs = [
            __('app.schedule') => '#',
            __('app.triggers') => route('triggers.index'),
            __('app.add_new_trigger') => '#',
        ];
        return view('triggers.create')->with(compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
    * Save data
    */
    public function store(TriggerRequest $request): RedirectResponse
    {
        $data = $this->_triggerData($request);
        $trigger = Trigger::create($data);
        activity('create')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.trigger') . " ({$request->name}) ". __('app.log_create')); // log

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


     /**
    * Retrun edit view
    */
    public function edit(Trigger $trigger): View
    {
        Helper::checkPermissions('schedule_triggers'); // check user permission
        $page = 'schedule_triggers';
        $page_title = __('app.edit_trigger');
        $breadcrumbs = [
            __('app.schedule') => '#',
            __('app.triggers') => route('triggers.index'),
            __('app.edit_trigger') => '#',
        ];

        return view('triggers.edit')->with(compact('page', 'page_title', 'breadcrumbs', 'trigger'));
    }

    public function update(TriggerRequest $request, $id): RedirectResponse
    {
        $data = $this->_triggerData($request);
        $trigger = Trigger::findOrFail($id);
        $trigger->fill($data)->save();
        activity('update')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.trigger') . " ({$request->name}) ". __('app.log_update')); // log

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

    /**
    * Retrun data for store or update
    */
    public function _triggerData($request)
    {
        $input = $request->except('_token');
        // should be first to overwrite send_datetime attribute
        if($input['based_on'] == 'date') {
            $carbon = new \Carbon\Carbon();
            // It has the correct value as per UTC for a calander
            $send_datetime = date('Y-m-d H:i:s', strtotime("{$input['db_send_datetime']}"));
            // Convert future datetime into UTC datetime
            $offsetSeconds =  $carbon->now(Auth::user()->time_zone)->getOffset();
            $input['send_datetime'] = \Carbon\Carbon::parse($send_datetime, config('app.timezone'))->subSeconds($offsetSeconds);
        }

        if($input['from_detail'] == 'custom') {
            $input['from_detail_custom'] = json_encode([
                'from_name' => $input['from_name'],
                'from_email' => ($input['from_email_part1'] . '@' . $input['from_email_part2']),
                'reply_email' => $input['reply_email']
            ]);
        }

        $input['execution_datetime'] = \Carbon\Carbon::now();
        $input['sending_server_ids'] = json_encode($request->sending_server_ids);
        $input['attributes'] = json_encode($input);
        $input['user_id'] = Auth::user()->id;
        $input['app_id'] = Auth::user()->app_id;

        return $input;
    }

    /**
     * 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(Trigger::whereIn('id', $ids)->pluck('name')->toArray()));
          $destroy = Trigger::whereIn('id', $ids)->delete();
        } else {
          $names = Trigger::whereId($id)->value('name');
          $destroy = Trigger::destroy($id);
        }
        
        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.trigger') . " ({$names}) ". __('app.log_delete'));

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

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

    /**
    * Retrun data according to based on 
    */
    public function getBasedOnData($type, $action, $id=null)
    {
        $trigger = null;
        if(!empty($id)) {
          $trigger = Trigger::whereId($id)->app()->first();
        }
        return view('triggers.based_on_data')->with(compact('type', 'action', 'trigger'));
    }
}
