<?php

namespace App\Http\Controllers\Admin\Raharja;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use App\Model\Raharja\CategoryMesssage;
use App\Model\Raharja\Message;
use App\Model\Raharja\News;
use App\Model\Raharja\UserReceive;
use App\User;
use Yajra\Datatables\Datatables;
use Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Validator;
use Hashids;

//load modelmu
class MessageController extends Controller
{
    /**
     * Title untuk judul di web
     * route digunakan untuk tempat resource (file path) + routing (route/web) diusahain sama ya biar gak ngubah"
     */
    private $title      = 'Message';                 /**jangan lupa diganti*/
    private $route      = 'admin.message.';          //path awal foldernya ajah (misal folder di admin/dashboard) => 'admin.dashboard' | jangan lupa diganti
    private $header     = 'Message';
    private $sub_header = 'Message';
    private $url        = 'admin.raharja.message.';

     public function __construct()
    {
        DB::enableQueryLog();
        /** nyalakan jika sudah set rolenya, jika ini dinyalakan halaman ini tidak akan keluar */
        // $this->middleware('permission:searching-list|searching-create|searching-update|searching-delete', ['only' => ['index', 'create', 'update']]);
        // $this->middleware('permission:searching-create', ['only' => ['create', 'create_action']]);
        // $this->middleware('permission:searching-update', ['only' => ['update', 'update_action']]);
        // $this->middleware('permission:searching-delete', ['only' => ['delete']]);
    }

     /**
    * Ini contoh crud yang sudah jalan
    * index digunakna untuk tampilan awal dari menu yang akan dibuat
    * Untuk CRUD Biar cepat
    * Silahkan ganti
    * EloquentMu:: => dengan model anda
    * $id_modelmu => ganti dengan id di model anda
    * id_di_routenya => jangan lupa disesuaikan dengan yang dideclare di route
    */


    public function index()
    {
        Helper::swal();

        $data = [
            //bawaan
            'title'      => $this->title,
            'route'      => $this->route,
            'header'     => $this->header,
            'sub_header' => $this->sub_header,
        ];
        // dd($data);
        return view($this->url . 'index', $data);
    }
    public function getData($udd_id = null)
    {
        $query = Message::query();

        return Datatables::of($query)
            ->addIndexColumn()
            ->addColumn('aksi', function ($query) {

                /**cek role */
                $aksi = '';
                // if (Auth::user()->can('master-jenis-kantong-update')) {
                    // $aksi .= "<a href='" . route($this->route . 'send', ['data_id' => Hashids::encode($query->id)]) . "' class='btn btn-sm btn-primary btn-edit'>Kirim</a>";
                // }

                // if (Auth::user()->can('master-jenis-kantong-delete')) {
                    $aksi .= "<a href='javascript:;' data-route='" . route($this->route . 'delete_action', ['data_id' => Hashids::encode($query->id)]) . "' class='btn btn-danger btn-sm btn-delete'>Delete</a>";
                // }
                return $aksi;
            })
            ->rawColumns(['aksi'])
            ->toJson();
    }
    public function create()
    {
        $arr_category = CategoryMesssage::get();
        $data = [
            //bawaan
            'title'         => $this->title,
            'route'         => $this->route,
            'header'        => $this->header,
            'sub_header'    => $this->sub_header,
            'categories'    => $arr_category,

        ];

        Helper::swal();

        return view($this->url . 'create', $data);
    }

    public function create_action(Request $request)
    {
        //declare post untuk simpan semua request yang diinputkan oleh form name=""
        $post = $request->all();
        //dd($post);
        /**digunakan untuk set rule validator */
        $rules = [
            'title'    => 'required',
            'content'  => 'required',
            'category' => 'required',
        ];
        /**digunakan untuk set message dari validatornya yang akan keluar gimna, :attribue itu udah langsung mendeteksi inputtan dari name="attribue" */
        $alert = [
            'file'  => 'File maksimal 1MB'
        ];
        $validator = Validator::make($post, $rules, $alert);

        if ($validator->passes()) {
            /**menggunakan transaction */
            DB::beginTransaction();

            $set_data_message = [
                'category_message_id' => $post['category'],
                'title'               => $post['title'],
                'user_id'               => Auth::user()->id,
                'content'             => Helper::input_summernote($post['content']),
            ];

            $message = Message::create($set_data_message);

            if($post['keterangan_kirim'] == 'semua'){
                $arr_user = User::get()->pluck('id')->toArray();
            }else{
                $arr_user = $post['pilih_user'];
            }

            foreach($arr_user as $key => $value){
                $set_data_user_recive[] = [
                    'message_id' => $message->id,
                    'user_id'    => $value,
                    'created_at' => Carbon::now(),
                    'is_check'   => 0,
                ];
            }
            $user_receive = UserReceive::insert($set_data_user_recive);

            if ($message && $user_receive) {
                DB::commit();
                $message = 'Berhasil';
                return redirect(route($this->route . 'index'))->with('success', Helper::parsing_alert($message));
            } else {
                DB::rollback();
                $message = 'Gagal';
                return redirect()->back()->with('error', Helper::parsing_alert($message));
            }
        }
        /**kenapa menggunakan back ? karena baliknya pasti ke halaman sebelumnya */
        $message = Helper::parsing_alert($validator->errors()->all());
        return redirect()->back()->with('error', $message)->withInput();
    }


    public function delete_action($id_modelmu)
    {
        $id = Hashids::decode($id_modelmu);
        /**cek idnya apakah ada ? */

        if (!empty($id)) {

            $cek_data = Message::find($id[0]);
            if ($cek_data) {
                DB::beginTransaction();
                try {
                    $arr_user_receive = UserReceive::Where('message_id', $cek_data->id)->delete();
                    $delete = $cek_data->delete();
                    DB::commit();
                    $message = 'Sukses';
                    $response = [
                        'message' => $message,
                        'status'   => true,
                    ];
                    return response()->json($response);
                } catch (Exception $e) {
                    DB::rollback();
                    $message = 'Gagal';
                    $response = [
                        'message' => $message,
                        'status'   => false,
                    ];
                    return response()->json($response);
                }
            }
            $message = 'Id tidak ditemukan atau sudah dihapus';
            $response = [
                'message' => $message,
                'status'   => false,
            ];
            return response()->json($response);
        }
        $message = 'Id tdak ditemukan';
        $response = [
            'message' => $message,
            'status'   => false,
        ];
        return response()->json($response);
    }

    public function selectUser(Request $request){
        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }
        $term = trim($request['nama']);

        $user = User::take(10);

        if (!empty($request['not_in'])) {
            $id = collect($request['not_in']);
            $user = $user->whereNotIn('id', $id);
        }
        if (!empty($term)) {
            $user = $user->where('nama', 'like', '%' . $term . '%');
        }
        $user = $user->get();
        $response = [];

        foreach ($user as $key => $value) {
            $response[] = ['id' => $value->id, 'text' => $value->name ];
        }

        return response()->json($response);
    }

    public function send($data_id){
        $id = Hashids::decode($data_id);
        $query = Message::where('id', $id)->first();

        foreach($query->userReceive as $key => $value){
            $set_data_user_recive[] = [
                'message_id' => $query->id,
                'user_receive_id'    => $value->user_id,
                'author_id'    => $query->user_id,
                'title'      => $query->title,
                'content'    => $query->content,
                'category'   => $query->categoryMessage->name,
            ];
        }
        if($set_data_user_recive){
            $result = $set_data_user_recive;

            $res_status = true;
            $msg = 'Kirim Data';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, $result);

        }else {

            $res_status = false;
            $msg = 'Data tidak ditemukan';
            $status_msg = $msg;

            return $this->resSuccess(null, $res_status, $msg, $status_msg, null);
        }
    }
    public function resSuccess($param = null, $status = null, $msg = null, $status_msg = null, $result = null)
    {
        $response['response'] = array(
            'status'     => $status,
            'message'    => $msg,
            'status_msg' => $status_msg,
        );
        $response['param'] = !empty($param) ? $param : '';

        $response['results'] = $result;

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

}
