<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\NoticeType;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Website\Notice;
use App\Models\Website\Post;

class NoticesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:notice-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $query = Notice::select
                ([
                    'id',
                    'user_id',
                    'page_id',
                    'notice_type_id',
                    'notice_title',
                    'description',
                    'start_date',
                    'expiry_date',
                    'notice_file',
                    'page_url',
                    'is_flash_notice',
                    'new_flag',
                    'priority',
                    'status',
                ])
                ->whereNull('course_id')
                ->with('getUser')
                ->with('getPage')
                ->with('getNoticeType');

        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $query->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('notice_title', 'like', '%' . $search_query . '%');
            });

            $data = $query->paginate($sort_by);

            return view('website-setting.notices.table', compact('data'));
        } else {
            $data = $query->paginate(10);
            return view('website-setting.notices.index', compact('data'));
        }
    }

    public function create()
    {
        $priority    = Notice::max('priority');
        $priority    = $priority != '' ? $priority : 0;
        $page        = Post::select('id','title')->get();
        $notice_type = NoticeType::select('id','title')->get();

        return view('website-setting.notices.create', compact('page','notice_type','priority'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'notice_title' => 'required|unique:notices,notice_title,NULL,id,deleted_at,NULL',
            'start_date'   => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            // 'start_date',
            // 'expiry_date',
        ]);

        $data['is_flash_notice'] = isset($request->is_flash_notice) ? $request->is_flash_notice : 0;
        $data['new_flag']        = isset($request->new_flag) ? $request->new_flag : 0;

        $data['expiry_date'] = $request->expiry_date != '' && $request->expiry_date != '0000-00-00' &&  $request->expiry_date != Null ? date('Y-m-d', strtotime($request->expiry_date)) : null;
        $data['start_date'] = $request->start_date != '' && $request->start_date != '0000-00-00' &&  $request->start_date != Null ? date('Y-m-d', strtotime($request->start_date)) : null;

        if ($request->hasFile('notice_file')) {
            $path          = 'notices/' . date('Y') . '/' . date('M');
            $response      = uploadImage($path, $request->notice_file);

            if ($response['status'] == true) {
                $data['notice_file'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }

                return redirect()->back()->with('error', $response['message']);
            }
        }
        $data['user_id'] = Auth()->id();
        $notice = Notice::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Notice created successfully',
                'data'    => $notice
            ]);
        }

        return redirect()->route('Notices.index')
            ->with('success','Notice created successfully');
    }

    public function edit($id)
    {
        $data = Notice::find($id);
        $priority = Notice::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $user = User::select('id','name')->get();
        $page = Post::select('id','title')->get();
        $notice_type = NoticeType::select('id','title')->get();

        return view('website-setting.notices.edit', compact('user','page','notice_type','priority','data'));
    }

    // public function update(Request $request, $id)
    // {

    //     // dd($request->all());
    //     $validator = \Validator::make($request->all(), [
    //         'notice_title' => 'required|unique:notices,notice_title,'.$id.',id,deleted_at,NULL',
    //         'start_date' => 'required',
    //     ]);

    //     if ($validator->fails()) {
    //         if ($request->ajax()) {
    //             return response()->json([
    //                 'success' => false,
    //                 'message' => $validator->getMessageBag()->first(),
    //                 'data'    => []
    //             ]);
    //         }

    //         return redirect()->back()->with('error', $validator->getMessageBag()->first());
    //     }

    //     $data = $request->except([
    //         '_token',
    //         '_method',
    //         'start_date',
    //         'expiry_date',
    //         'notice_file',
    //     ]);

    //     $data['is_flash_notice'] = isset($request->is_flash_notice) ? $request->is_flash_notice : 0;
    //     $data['new_flag']        = isset($request->new_flag) ? $request->new_flag : 0;
    //     $data['start_date']      = $request->start_date  != '' && $request->start_date  != '0000-00-00' &&  $request->start_date  != Null ? date('Y-m-d', strtotime($request->start_date)) : null;
    //     $data['expiry_date']     = $request->expiry_date != '' && $request->expiry_date != '0000-00-00' &&  $request->expiry_date != Null ? date('Y-m-d', strtotime($request->expiry_date)) : null;


    //     $data['user_id'] = Auth()->id();

    //     $record = Notice::find($id);

    //     if ($request->hasFile('notice_file')) {
    //         $path          = 'notices/' . date('Y') . '/' . date('M');
    //         $response      = uploadImage($path, $request->notice_file, $record->notice_file);

    //         if ($response['status'] == true) {
    //             $data['notice_file'] = $response['file_name'];
    //         } else {
    //             if ($request->ajax()) {
    //                 return response()->json([
    //                     'success' => false,
    //                     'message' => $response['message'],
    //                     'data'    => []
    //                 ]);
    //             }

    //             return redirect()->back()->with('error', $response['message']);
    //         }
    //     }

    //     $data = Notice::whereId($id)->update($data);
    //     $data = Notice::find($id);

    //     $data->update($data);

    //     if ($request->ajax()) {
    //         return response()->json([
    //             'success' => true,
    //             'message' => 'Notice Updated successfully',
    //             'data'    => $data
    //         ]);
    //     }
    // }
    public function update(Request $request, $id)
{
    $validator = \Validator::make($request->all(), [
        'notice_title' => 'required|unique:notices,notice_title,' . $id . ',id,deleted_at,NULL',
        'start_date'   => 'required',
    ]);

    if ($validator->fails()) {
        if ($request->ajax()) {
            return response()->json([
                'success' => false,
                'message' => $validator->getMessageBag()->first(),
                'data'    => []
            ]);
        }

        return redirect()->back()->with('error', $validator->getMessageBag()->first());
    }

    $data = $request->except([
        '_token',
        '_method',
        'start_date',
        'expiry_date',
    ]);

    $data['is_flash_notice'] = isset($request->is_flash_notice) ? $request->is_flash_notice : 0;
    $data['new_flag']        = isset($request->new_flag) ? $request->new_flag : 0;

    $data['start_date']  = $request->start_date  != '' && $request->start_date  != '0000-00-00' &&  $request->start_date  != Null ? date('Y-m-d', strtotime($request->start_date)) : null;
    $data['expiry_date'] = $request->expiry_date != '' && $request->expiry_date != '0000-00-00' &&  $request->expiry_date != Null ? date('Y-m-d', strtotime($request->expiry_date)) : null;

    if ($request->hasFile('notice_file')) {
        $path     = 'notices/' . date('Y') . '/' . date('M');
        $response = uploadImage($path, $request->notice_file);

        if ($response['status'] == true) {
            $data['notice_file'] = $response['file_name'];
        } else {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $response['message'],
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $response['message']);
        }
    }

    $data['user_id'] = auth()->id();

    $notice = Notice::where('id', $id)->update($data);

    if ($request->ajax()) {
        return response()->json([
            'success' => true,
            'message' => 'Notice updated successfully',
            'data'    => $notice
        ]);
    }

    return redirect()->route('notices.index')->with('success', 'Notice updated successfully');
}

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

            $Redirect = 'notices';

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



    public function destroy(Request $request)
    {
        $data = Notice::find($request->id);

        Notice::find($request->id)->delete();

        $Redirect = 'Notices';

        return response()->json([
            'success' => true,
            'message' => ['Notices Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }

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

            $Redirect = 'notices';

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

}
