<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RmsEvent;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class RmsEventController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $events = RmsEvent::where('archived', 0)->get();
        } else {
            $events = RmsEvent::whereDate('end_date', '>=', Carbon::now()->toDateTimeString())
                ->where('archived', 0)
                ->orWhere(function($query) {
                    $query->where('end_date', 'null')
                          ->where('archived', 0);
                })
                ->get();
        }

        $eventJson = [];

        foreach ($events As $key => $event) {
            if ((Auth::user()->username == 'drdanesh' || Auth::user()->username == 'witel')) {
                $isAdmin = 2;
            } elseif (Auth::user()->id < 470 && Auth::user()->province_id != null && Auth::user()->city_id == null) {
                $isAdmin = 1;
            } else {
                $isAdmin = 0;
            }

            $eventJson[$key] = [
                'id' => $event->id,
                'title' => $event->title,
                'description' => $event->description ?? '-',
                'image' => ($event->path_image) ? asset('storage' . substr($event->path_image, 6)) : 'https://rms.rmto.ir/storage/no-image-1.jpg',
                'deadline' => ($event->end_date) ? verta($event->end_date)->format('Y/m/d') : '-',
                'files' => ($event->path_file) ? asset('storage' . substr($event->path_file, 6)) : null,
                'admin' => $isAdmin
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $eventJson
        ], 200);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            return view('rmto-preview.pages.management.event-add');
        } else {
            return redirect('rmto');
        }
    }

    /**
     * Show event list page.
     *
     * @return \Illuminate\Http\Response
     */
    public function userEventList()
    {
        return view('rmto-preview.pages.management.event-list');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storeEvent(Request $request)
    {
        $request->validate([
            'title' => 'required|string',
            'description' => 'string',
            'deadline' => 'date_format:U',
            'files' => 'file',
            'image' => 'image'
        ]);

        $event = new RmsEvent;

        $event->user_id = Auth::user()->id;
        $event->title = $request->input('title') ?? null;
        $event->description = $request->input('description') ?? null;
        if ($request->input('deadline')) {
            $event->end_date = date('Y-m-d 23:59:59', (int)substr($request->input('deadline'), 0, 10));
        }
        if ($request->file('files')) {
            $event->path_file = $request->file('files')->storeAs(
                'public/events/files',
                time() . '_' . $request->file('files')->getClientOriginalName()
            );
        }
        if ($request->file('image')) {
            $event->path_image = $request->file('image')->store('public/events/images');
        }

        $event->save();

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $event
        ], 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $event = RmsEvent::findOrFail($id);

            return view('rmto-preview.pages.management.event-edit', ['event' => $event]);
        } else {
            return redirect('rmto');
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'title' => 'required|string',
            'description' => 'string',
            'deadline' => 'date_format:U',
            'files' => 'file',
            'image' => 'image'
        ]);

        $event = RmsEvent::find($id);

        $event->user_id = Auth::user()->id;
        $event->title = $request->input('title') ?? null;
        $event->description = $request->input('description') ?? null;
        if ($request->input('deadline')) {
            $event->end_date = date('Y-m-d 23:59:59', (int)substr($request->input('deadline'), 0, 10));
        } else {
            $event->end_date = null;
        }
        if ($request->file('files')) {
            $event->path_file = $request->file('files')->storeAs(
                'public/events/files',
                time() . '_' . $request->file('files')->getClientOriginalName()
            );
        }
        if ($request->file('image')) {
            $event->path_image = $request->file('image')->store('public/events/images');
        }

        $event->save();

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $event
        ], 201);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $event = RmsEvent::find($id);

            $event->delete();

            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $event
            ], 200);
        } else {
            return response()->json([
                'status' => 'succeed',
                'message' => ''
            ], 200);
        }
    }

    /**
     * User download an event file.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function userDownloadEvent($id)
    {
        $event = RmsEvent::find($id);

        $eventHistory = $event->eventHistories()->firstOrNew([
            'user_id' => Auth::user()->id,
            'status' => 1
        ]);

        $eventHistory->updated_at = Carbon::now()->toDateTimeString();

        $eventHistory->save();

        return Storage::download($event->path_file);
    }

    /**
     * User upload an event file.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function userUploadEvent(Request $request, $id)
    {
        $event = RmsEvent::find($id);

        $eventHistory = $event->eventHistories()->create([
            'user_id' => Auth::user()->id,
            'status' => 2,
            'path_file' => $request->file('files')->storeAs(
                'public/events/users/files',
                time() . '_' . $request->file('files')->getClientOriginalName()
            )
        ]);

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $eventHistory
        ], 201);
    }

    /**
     * Get histories for an event.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function getEventHistories($id) {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh'
            || (Auth::user()->province_id != null && Auth::user()->city_id == null && Auth::user()->id < 470)) {
            if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
                $provinces = \App\Models\User::where('province_id', '<>', null)
                    ->where('city_id', '=', null)
                    ->where('id', '<=', 35)
                    ->get();

                $histories = [];
                $historyIndex = 0;
                $itemCount = 0;
                $downloadCount = 0;
                $uploadCount = 0;

                foreach ($provinces As $province) {
                    $users = \App\Models\User::where('province_id', '=', $province->id)
                        ->where('id', '>', 35)
                        ->whereNotBetween('id', [466, 470])
                        ->get();

                    $histories[$historyIndex]['province_id'] = $province->id;
                    $histories[$historyIndex]['province_name'] = $province->name;
                    $histories[$historyIndex]['main_province_name'] = $province->name;
                    $downloadHistory = $province->eventHistories()
                        ->where('rms_event_id', '=', $id)
                        ->where('status', '=', 1)
                        ->orderByDesc('updated_at')->limit(1)
                        ->get();
                    $uploadHistory = $province->eventHistories()
                        ->where('rms_event_id', '=', $id)
                        ->where('status', '=', 2)
                        ->orderByDesc('updated_at')->limit(1)
                        ->get();
                    $histories[$historyIndex]['downloaded_at'] = $downloadHistory[0]->updated_at ?? null;
                    $histories[$historyIndex]['uploaded_at'] = $uploadHistory[0]->updated_at ?? null;

                    if ($histories[$historyIndex]['downloaded_at']) {
                        $downloadCount++;
                    }
                    if ($histories[$historyIndex]['uploaded_at']) {
                        $uploadCount++;
                    }

                    if (isset($uploadHistory[0]) && $uploadHistory[0]->path_file) {
                        $histories[$historyIndex]['file'] = asset('storage' . substr($uploadHistory[0]->path_file, 6));
                    } else {
                        $histories[$historyIndex]['file'] = null;
                    }
                        
                    $historyIndex++;

                    foreach ($users As $user) {
                        $histories[$historyIndex]['province_id'] = $user->id;
                        $histories[$historyIndex]['province_name'] = $user->name;
                        $histories[$historyIndex]['main_province_name'] = $province->name;
                        $downloadHistory = $user->eventHistories()
                            ->where('rms_event_id', '=', $id)
                            ->where('status', '=', 1)
                            ->orderByDesc('updated_at')->limit(1)
                            ->get();
                        $uploadHistory = $user->eventHistories()
                            ->where('rms_event_id', '=', $id)
                            ->where('status', '=', 2)
                            ->orderByDesc('updated_at')->limit(1)
                            ->get();
                        $histories[$historyIndex]['downloaded_at'] = $downloadHistory[0]->updated_at ?? null;
                        $histories[$historyIndex]['uploaded_at'] = $uploadHistory[0]->updated_at ?? null;

                        if ($histories[$historyIndex]['downloaded_at']) {
                            $downloadCount++;
                        }
                        if ($histories[$historyIndex]['uploaded_at']) {
                            $uploadCount++;
                        }

                        if (isset($uploadHistory[0]) && $uploadHistory[0]->path_file) {
                            $histories[$historyIndex]['file'] = asset('storage' . substr($uploadHistory[0]->path_file, 6));
                        } else {
                            $histories[$historyIndex]['file'] = null;
                        }
                        
                        $historyIndex++;
                    }

                    $itemCount = $historyIndex;
                }
            } else {
                $users = \App\Models\User::where('province_id', '=', Auth::user()->province_id)
                    ->whereNotBetween('id', [466, 470])
                    ->get();
                
                $histories = [];
                $historyIndex = 0;
                $itemCount = 0;
                $downloadCount = 0;
                $uploadCount = 0;

                foreach ($users As $user) {
                    $histories[$historyIndex]['province_id'] = $user->id;
                    $histories[$historyIndex]['province_name'] = $user->name;
                    $histories[$historyIndex]['main_province_name'] = null;

                    $downloadHistory = $user->eventHistories()
                        ->where('rms_event_id', '=', $id)
                        ->where('status', '=', 1)
                        ->orderByDesc('updated_at')->limit(1)
                        ->get();
                    $uploadHistory = $user->eventHistories()
                        ->where('rms_event_id', '=', $id)
                        ->where('status', '=', 2)
                        ->orderByDesc('updated_at')->limit(1)
                        ->get();
                    $histories[$historyIndex]['downloaded_at'] = $downloadHistory[0]->updated_at ?? null;
                    $histories[$historyIndex]['uploaded_at'] = $uploadHistory[0]->updated_at ?? null;

                    if ($histories[$historyIndex]['downloaded_at']) {
                        $downloadCount++;
                    }
                    if ($histories[$historyIndex]['uploaded_at']) {
                        $uploadCount++;
                    }

                    if (isset($uploadHistory[0]) && $uploadHistory[0]->path_file) {
                        $histories[$historyIndex]['file'] = asset('storage' . substr($uploadHistory[0]->path_file, 6));
                    } else {
                        $histories[$historyIndex]['file'] = null;
                    }
                    
                    $historyIndex++;
                }

                $itemCount = $historyIndex;
            }

            return view('rmto-preview.pages.management.event-history', [
                'events' => $histories,
                'itemCount' => [
                    'itemCount' => $itemCount,
                    'downloadCount' => $downloadCount,
                    'uploadCount' => $uploadCount
                ]
            ]);
        } else {
            return redirect('rmto');
        }
    }

    /**
     * Archive the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function archiveEvent($id)
    {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            $event = RmsEvent::find($id);

            $event->archived = 1;

            $event->save();

            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $event
            ], 200);
        } else {
            return response()->json([
                'status' => 'succeed',
                'message' => ''
            ], 200);
        }
    }

    /**
     * Display a listing of the archived resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function indexArchivedEvent()
    {
        $events = RmsEvent::where('archived', 1)->get();

        $eventJson = [];

        foreach ($events As $key => $event) {
            $eventJson[$key] = [
                'id' => $event->id,
                'title' => $event->title,
                'description' => $event->description ?? '-',
                'image' => ($event->path_image) ? asset('storage' . substr($event->path_image, 6)) : 'https://rms.rmto.ir/storage/no-image-1.jpg',
                'deadline' => ($event->end_date) ? verta($event->end_date)->format('Y/m/d') : '-',
                'files' => ($event->path_file) ? asset('storage' . substr($event->path_file, 6)) : null
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $eventJson
        ], 200);
    }

    public function getArchivedEventPage()
    {
        if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {
            return view('rmto-preview.pages.management.event-archive');
        } else {
            return redirect('rmto');
        }
    }
}
