<?php

namespace App\Http\Controllers;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\SubscriberExport;
use App\Models\Subscriber;
use Illuminate\Http\Request;

class SubscriberController extends Controller
{
    public function list(Request $request)
    {
        $user = auth()->user();
        $subscribers = $user->subscribers()->orderBy('id', 'desc')->search($request->search)->paginate()->appends($request->all());
        return view('/subscriber-list', compact('subscribers'));
    }

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

    public function export(Request $request)
    {
    return Excel::download(new SubscriberExport(), 'subscribers.xlsx');
    }

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