<?php

namespace App\Http\Controllers;

use Helper;
use App\Models\Autoreply;
use App\Models\User;
use Illuminate\Http\Request;

class AutoreplyController extends Controller
{
  public function list()
  {
    $adminUsers = User::where('role', '=', 'admin')->get();
    $userUsers = User::where('role', '=', 'user')->get();
    $user = auth()->user();
    $devices = $user->devices;
    $autoreplies = $user
      ->autoreplies()
      ->orderBy('id', 'asc')
      ->get();
    $numOfButtons = empty(Helper::setting('numOfButtons')) ? 3 : Helper::setting('numOfButtons');
    $numOfLists = empty(Helper::setting('numOfLists')) ? 5 : Helper::setting('numOfLists');
    return view('/autoreply-list', compact('adminUsers', 'userUsers', 'devices', 'autoreplies', 'numOfButtons', 'numOfLists'));
  }

  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();
    $package = $user->package;
    $countAutoreply = $user->autoreplies()->count();
    if (Helper::isEx() && $package->max_autoreply <= $countAutoreply && $package->max_autoreply >= 0) {
      return redirect()
        ->back()
        ->with('danger_alert', __('Autoreply reached max limit! Max') . ': ' . $package->max_autoreply);
    }
    $user_id = $user->id;
    $numOfButtons = empty(Helper::setting('numOfButtons')) ? 3 : Helper::setting('numOfButtons');
    $numOfLists = empty(Helper::setting('numOfLists')) ? 3 : Helper::setting('numOfLists');
    if (!empty($request->mediafile)) {
      //$media_ext = $request->mediafile->getClientOriginalExtension();
      $file = Helper::normalize($request->mediafile->getClientOriginalName());
      $mediafile = pathinfo($file, PATHINFO_FILENAME) . '-' . rand(111111, 999999) . '.' . pathinfo($file, PATHINFO_EXTENSION);
      $mediaurl = url("/users/{$user_id}/autoreply/{$mediafile}");
      $media_upload = $request->mediafile->move(public_path("users/{$user_id}/autoreply"), $mediafile);
    } else {
      // $mediafile = '';
      $mediaurl = '';
    }
    $autoreply = new Autoreply();
    $autoreply->user_id = $user_id;
    $autoreply->sender = $request->input('sender');
    $autoreply->keyword = $request->input('keyword');
    if (
      Autoreply::where('user_id', '=', $user_id)
        ->where('sender', '=', $request->input('sender'))
        ->where('keyword', '=', $autoreply->keyword)
        ->count() > 0
    ) {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('Duplicate found. Failed to add') . ': ' . $autoreply->keyword]);
    }
    $autoreply->match_percent = $request->input('match_percent');
    $autoreply->response = $request->input('response');
    // $autoreply->mediafile = $mediafile;
    $autoreply->mediaurl = $mediaurl;
    $autoreply->save();

    if ($request->input('buttontype') === 'reply') {
      $data['replyButtons'] = [];
      for ($i = 1; $i <= $numOfButtons; $i++) {
        if (!empty($request->input('displayText' . $i))) {
          $arr = ['buttonId' => $request->input('responseText' . $i), 'buttonText' => ['displayText' => $request->input('displayText' . $i)], 'type' => 1];
          array_push($data['replyButtons'], $arr);
        }
      }
    } elseif ($request->input('buttontype') === 'template') {
      $data['templateButtons'] = [];
      for ($i = 1; $i <= $numOfButtons; $i++) {
        if (!empty($request->input('displayText' . $i))) {
          if (str_starts_with($request->input('responseText' . $i), 'http')) {
            $restype[$i] = 'url';
            $buttype[$i] = 'urlButton';
          } elseif (str_starts_with($request->input('responseText' . $i), '+')) {
            $restype[$i] = 'phoneNumber';
            $buttype[$i] = 'callButton';
          } else {
            $restype[$i] = 'id';
            $buttype[$i] = 'quickReplyButton';
          }
          $arr = ['index' => $i, $buttype[$i] => ['displayText' => $request->input('displayText' . $i), $restype[$i] => $request->input('responseText' . $i)]];
          array_push($data['templateButtons'], $arr);
        }
      }
    } elseif ($request->input('buttontype') === 'list') {
      $sectionTitle = 'startSection';
      $data['listButtons'] = [];
      $rows['rows'] = [];
      for ($i = 1; $i <= $numOfLists; $i++) {
        if ($sectionTitle === 'startSection' || $sectionTitle === $request->input('sectionTitle' . $i)) {
          $sectionTitle = $request->input('sectionTitle' . $i);
          if (!empty($request->input('rowTitle' . $i))) {
            $arrRow = ['title' => $request->input('rowTitle' . $i), 'description' => $request->input('description' . $i), 'rowId' => $request->input('rowId' . $i)];
            array_push($rows['rows'], $arrRow);
          }
        } else {
          $arrSection = ['title' => $sectionTitle, 'rows' => $rows['rows']];
          array_push($data['listButtons'], $arrSection);
          $rows['rows'] = [];
          $sectionTitle = $request->input('sectionTitle' . $i);
          if (!empty($request->input('rowTitle' . $i))) {
            $arrRow = ['title' => $request->input('rowTitle' . $i), 'description' => $request->input('description' . $i), 'rowId' => $request->input('rowId' . $i)];
            array_push($rows['rows'], $arrRow);
          }
        }
      }
      $arrSection = ['title' => $sectionTitle, 'rows' => $rows['rows']];
      array_push($data['listButtons'], $arrSection);
      $rows['rows'] = [];
    }

    $data['footerText'] = $request->input('footerText');
    $data['mainTitle'] = $request->input('mainTitle');
    $data['buttonText'] = $request->input('buttonText');
    $autoreply->data = str_replace(',{"title":null,"rows":[]}', '', json_encode($data));
    $autoreply->save();

    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully add') . ': ' . $autoreply->keyword]);
  }

  public function update(Request $request)
  {
    $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;
    $numOfButtons = empty(Helper::setting('numOfButtons')) ? 3 : Helper::setting('numOfButtons');
    $numOfLists = empty(Helper::setting('numOfLists')) ? 3 : Helper::setting('numOfLists');
    if (!empty($request->mediafile)) {
      if (!empty($request->input('prev_mediafile')) && file_exists(public_path("users/{$user_id}/autoreply/{$request->input('prev_mediafile')}"))) {
        unlink(public_path("users/{$user_id}/autoreply/{$request->input('prev_mediafile')}"));
      }
      //$media_ext = $request->mediafile->getClientOriginalExtension();
      $file = Helper::normalize($request->mediafile->getClientOriginalName());
      $mediafile = pathinfo($file, PATHINFO_FILENAME) . '-' . rand(111111, 999999) . '.' . pathinfo($file, PATHINFO_EXTENSION);
      $mediaurl = url("/users/{$user_id}/autoreply/{$mediafile}");
      $media_upload = $request->mediafile->move(public_path("users/{$user_id}/autoreply"), $mediafile);
    } else {
      // $mediafile = $request->input('prev_mediafile');
      $mediaurl = $request->input('prev_mediaurl');
    }
    $autoreply = Autoreply::where('id', '=', $request->input('autoreply_id'))->first();
    if ($user_id != $autoreply->user_id && auth()->user()->role !== 'admin') {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You are not allowed to update Autoreply')]);
    }
    $autoreply->sender = $request->input('sender');
    $autoreply->keyword = $request->input('keyword');
    if (
      Autoreply::where('user_id', '=', $user_id)
        ->where('sender', '=', $request->input('sender'))
        ->where('keyword', '=', $request->input('keyword'))
        ->count() > 0
    ) {
      if ($request->input('keyword') != $request->input('prev_keyword')) {
        return redirect()
          ->back()
          ->with(['danger_alert' => __('Duplicate found. Failed to edit') . ': ' . $request->input('keyword')]);
      }
    }
    $autoreply->match_percent = $request->input('match_percent');
    $autoreply->response = $request->input('response');
    // $autoreply->mediafile = $mediafile;
    $autoreply->mediaurl = $mediaurl;
    $autoreply->save();

    if ($request->input('buttontype') === 'reply') {
      $data['replyButtons'] = [];
      for ($i = 1; $i <= $numOfButtons; $i++) {
        if (!empty($request->input('displayText' . $i))) {
          $arr = ['buttonId' => $request->input('responseText' . $i), 'buttonText' => ['displayText' => $request->input('displayText' . $i)], 'type' => 1];
          array_push($data['replyButtons'], $arr);
        }
      }
    } elseif ($request->input('buttontype') === 'template') {
      $data['templateButtons'] = [];
      for ($i = 1; $i <= $numOfButtons; $i++) {
        if (!empty($request->input('displayText' . $i))) {
          if (str_starts_with($request->input('responseText' . $i), 'http')) {
            $restype[$i] = 'url';
            $buttype[$i] = 'urlButton';
          } elseif (str_starts_with($request->input('responseText' . $i), '+')) {
            $restype[$i] = 'phoneNumber';
            $buttype[$i] = 'callButton';
          } else {
            $restype[$i] = 'id';
            $buttype[$i] = 'quickReplyButton';
          }
          $arr = ['index' => $i, $buttype[$i] => ['displayText' => $request->input('displayText' . $i), $restype[$i] => $request->input('responseText' . $i)]];
          array_push($data['templateButtons'], $arr);
        }
      }
    } elseif ($request->input('buttontype') === 'list') {
      $sectionTitle = 'startSection';
      $data['listButtons'] = [];
      $rows['rows'] = [];
      for ($i = 1; $i <= $numOfLists; $i++) {
        if ($sectionTitle === 'startSection' || $sectionTitle === $request->input('sectionTitle' . $i)) {
          $sectionTitle = $request->input('sectionTitle' . $i);
          if (!empty($request->input('rowTitle' . $i))) {
            $arrRow = ['title' => $request->input('rowTitle' . $i), 'description' => $request->input('description' . $i), 'rowId' => $request->input('rowId' . $i)];
            array_push($rows['rows'], $arrRow);
          }
        } else {
          $arrSection = ['title' => $sectionTitle, 'rows' => $rows['rows']];
          array_push($data['listButtons'], $arrSection);
          $rows['rows'] = [];
          $sectionTitle = $request->input('sectionTitle' . $i);
          if (!empty($request->input('rowTitle' . $i))) {
            $arrRow = ['title' => $request->input('rowTitle' . $i), 'description' => $request->input('description' . $i), 'rowId' => $request->input('rowId' . $i)];
            array_push($rows['rows'], $arrRow);
          }
        }
      }
      $arrSection = ['title' => $sectionTitle, 'rows' => $rows['rows']];
      array_push($data['listButtons'], $arrSection);
      $rows['rows'] = [];
    }

    $data['footerText'] = $request->input('footerText');
    $data['mainTitle'] = $request->input('mainTitle');
    $data['buttonText'] = $request->input('buttonText');
    $autoreply->data = str_replace(',{"title":null,"rows":[]}', '', json_encode($data));
    $autoreply->save();

    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully edit') . ': ' . $autoreply->keyword]);
  }

  public function samples($user_id)
  {
    $autoreplies = [
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => 'main menu',
        'match_percent' => 100,
        'response' => "Hi {name}! Welcome to Sample Autoreply Menu system!\nPlease type a number below:\n\n1. This will show level-1 option-1 response message\n2. This will show level-1 option-2 response message\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => '#1',
        'match_percent' => 100,
        'response' => "Great! You chose 1. This is the response of level-1 menu if you type 1 previously.\n Now you can ask more question here:\n1. Show me a heart\n2. Show me a monkey\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => '#2',
        'match_percent' => 100,
        'response' => "Great! You chose 2. This is the response of level-1 menu if you type 2 previously.\n Now you can ask more question here:\n1. Show me a burger\n2. Show me a chicken\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => '#1#1',
        'match_percent' => 100,
        'response' => "This is the response of level-2 menu if you type 1 previously. As promised, here is the ❤️\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => '#1#2',
        'match_percent' => 100,
        'response' => "This is the response of level-2 menu if you type 2 previously. As promised, here is the 🐒\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => '#2#1',
        'match_percent' => 100,
        'response' => "This is the response of level-2 menu if you type 1 previously. As promised, here is the 🍔\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => '#2#2',
        'match_percent' => 100,
        'response' => "This is the response of level-2 menu if you type 2 previously. As promised, here is the 🐔\n\n*main menu*\n*back*",
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => 'vcard',
        'match_percent' => 100,
        'response' => 'FN: My Full Name,
ORG: My Company Name,
TEL: 14088999448',
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => 'location',
        'match_percent' => 100,
        'response' => 'degreesLatitude: 24.232483,
degreesLongitude: 55.692107,
locationName: Omar Palace,
locationAddress: Abu Dhabi',
      ],
      [
        'user_id' => $user_id,
        'sender' => 'all',
        'keyword' => 'poll',
        'match_percent' => 100,
        'response' => '"poll":{
"name": "hello there!",
"values": ["test123", "test231"],
"selectableCount": 1
}',
      ],
    ];

    foreach ($autoreplies as $autoreply) {
      if (
        Autoreply::where('user_id', '=', $autoreply['user_id'])
          ->where('keyword', '=', $autoreply['keyword'])
          ->count() == 0
      ) {
        Autoreply::insert($autoreply);
      } else if ($autoreply['keyword'] === 'main menu') break;  
    }
    return redirect()
    ->back()
    ->with(['success_alert' => __('Successfully') . ': ' . __('Insert Autoreply Samples')]);
  }

  public function copy(Request $request)
  {
    if (!empty($request->to_sender)) {
      $fromAutoreply = Autoreply::where('id', '=', $request->autoreply_id)->first();
      Autoreply::updateOrInsert(
        ['user_id' => auth()->user()->id, 'sender' => $request->to_sender, 'keyword' => $request->autoreply_keyword],
        ['match_percent' => $fromAutoreply->match_percent, 'response' => $fromAutoreply->response, 'data' => $fromAutoreply->data, 'mediaurl' => $fromAutoreply->mediaurl]
      );
      return redirect()
        ->back()
        ->with(['success_alert' => __('Successfully copy') . ': ' . $fromAutoreply->keyword . ' ' . __('To') . ' ' . $request->to_sender]);
    } elseif (!empty($request->to_userid)) {
      $to_id = $request->to_userid;
      $to_name = User::where('id', '=', $to_id)->value('name');
      $fromAutoreply = Autoreply::where('id', '=', $request->autoreply_id)->first();
      Autoreply::updateOrInsert(
        ['user_id' => $to_id, 'sender' => 'all', 'keyword' => $request->autoreply_keyword],
        ['match_percent' => $fromAutoreply->match_percent, 'response' => $fromAutoreply->response, 'data' => $fromAutoreply->data, 'mediaurl' => $fromAutoreply->mediaurl]
      );
      return redirect()
        ->back()
        ->with(['success_alert' => __('Successfully copy') . ': ' . $fromAutoreply->keyword . ' ' . __('To') . ' ' . $request->to_name]);
    }
  }

  public function remove(Request $request)
  {
    $autoreply = Autoreply::where('id', '=', $request->autoreply_id)->first();
    if (auth()->user()->id != $autoreply->user_id && auth()->user()->role !== 'admin') {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You are not allowed to delete Autoreply')]);
    }
    if ($request->action === 'button') {
      $autoreply->data = null;
    } elseif ($request->action === 'media') {
      $arrMediaurl = explode('/', $autoreply->mediaurl);
      $mediafile = end($arrMediaurl);
      if (file_exists(public_path("users/{$autoreply->user_id}/autoreply/{$mediafile}"))) {
        unlink(public_path("users/{$autoreply->user_id}/autoreply/{$mediafile}"));
      }
      // $autoreply->mediafile = null;
      $autoreply->mediaurl = null;
    }
    $autoreply->save();
    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully delete Autoreply') . ' ' . $request->action]);
  }

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