<?php

namespace App\Http\Controllers;

use Excel;
use App\Exports\MessageExport;
use App\Models\Message;
use Illuminate\Http\Request;

class MessageController extends Controller
{
    public function list(Request $request)
    {
        $messages = Message::where('user_id', auth()->user()->id)->latest()->search($request->search)->paginate()->appends($request->all());
        $listAll = false;
        return view('/message-list', compact('listAll', 'messages'));
    }

    public function listAll(Request $request)
    {
        $messages = Message::latest()->search($request->search)->paginate()->appends($request->all());
        $listAll = true;
        return view('/message-list', compact('listAll', 'messages'));
    }

    public function update(Request $request)
    {
        $user = auth()->user();
        $message = Message::where('id', '=', $request->input('message_id'))->first();
        if ($user->id != $message->user_id && $user->role !== 'admin') return redirect()->back()->with(['danger_alert' => __('You are not allowed to update Message')]);
        $message->user_id = $user->id;
        $message->sender = $request->input('sender');
        $message->name = $request->input('name');
        $message->phone = $request->input('phone');
        $message->status = $request->input('status');
        $message->save();
        return redirect()->back()->with(['success_alert' => __('Successfully update Message') . ': ' . $message->sender]);
    }

    public function export(Request $request)
    {
        return Excel::download(new MessageExport($request->listAll), 'messages.xlsx');
    }

    public function destroy(Request $request)
    {
        $user = auth()->user();
        $message = Message::where('id', '=', $request->message_id)->first();
        if ($user->id != $message->user_id && $user->role !== 'admin') return redirect()->back()->with(['danger_alert' => __('You are not allowed to delete Message')]);
        $message->delete();
        return redirect()->back()->with(['success_alert' => __('Successfully delete Message')]);
    }

    public function destroyAll(Request $request)
    {
        $user = auth()->user();
        $messages = Message::where('user_id', '=', $user->id)->delete();
        return redirect()->back()->with(['success_alert' => __('Successfully delete Message')]);
    }
}
