<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\NewsLatter;
use Illuminate\Http\Request;

class NewsLetterController extends Controller
{
    public function index(Request $request)
    {
        $NewsLatters = NewsLatter::select(['id', 'email', 'status', 'created_at']);
        $sort_by        = $request->get('sortby') ?? 10;
        $sort_type      = $request->get('sorttype');
        $query          = $request->get('query');

        if (!empty($query) && !empty($sort_by) && $query != " ") {

            $NewsLatters->where('email', 'like', '%' . $query . '%');
        }
        $NewsLatter = $NewsLatters->orderBy('id', 'desc')->paginate($sort_by);
        if ($request->ajax()) {
            return view('website-setting.news-letter.table', compact('NewsLatter'));
        } else {
            return view('website-setting.news-letter.index', compact('NewsLatter'));
        }
    }



    public function changestatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = NewsLatter::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Status successfully change'],
                    'data' => [
                        'redirect' => '',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $Delete = NewsLatter::where(['id' => $request->id])->delete();
        $Redirect = '';
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }
}
