<?php

namespace App\Http\Controllers\Admin;

use App\Models\Story;
use App\Models\Video;
use App\Models\Festivals;
use App\Models\FeaturePost;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\FestivalsFrame;
use App\Models\StorageSetting;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class FestivalsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:Festival');
    }

    public function index(Request $request)
    {
        $from_date = !empty($request->from_date) ? $request->from_date : "";
        $end_date = !empty($request->to_date) ? $request->to_date : "";
        $search = !empty($request->search) ? $request->search : "";

        $index['data'] = Festivals::where(function ($query) use ($from_date, $end_date) {
            if (!empty($from_date)) {
                $query->where('festivals_date', '>=', $from_date);
            }
            if (!empty($end_date)) {
                $query->where('festivals_date', '<=', $end_date);
            }
        })->where(function ($query) use ($search) {
            if (!empty($search)) {
                $query->where("title", 'LIKE', '%' . $search . '%');
            }
        })
            ->paginate(12);
        $index['festival'] = Festivals::get();
        return view("festivals.index", $index);
    }

    public function create()
    {
        return view("festivals.create");
    }

    public function store(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'title' => 'required',
            "image" => "nullable|mimes:jpg,png,jpeg",
            "festivals_date" => 'required',
            "activation_date" => 'required',
        ]);

        if ($validation->fails()) {
            return back()->withErrors($validation)->withInput();
        } else {
            $id = Festivals::create([
                "title" => $request->get("title"),
                "festivals_date" => date_format(date_create(implode("", preg_split("/[-\s:,]/", $request->get("festivals_date")))), "Y-m-d"),
                "activation_date" => date_format(date_create(implode("", preg_split("/[-\s:,]/", $request->get("activation_date")))), "Y-m-d"),
            ])->id;

            if (StorageSetting::getStorageSetting("storage") == "DigitalOcean") {
                if ($request->file("image") && $request->file('image')->isValid()) {
                    $image = $request->file('image');
                    $file = Str::uuid() . '.' . $image->getClientOriginalExtension();

                    $path = Storage::disk('spaces')->put('uploads/' . $file, file_get_contents($image), 'public');

                    $f = Festivals::find($id);
                    $f->image = $file;
                    $f->save();
                }
            } else {
                if ($request->file("image") && $request->file('image')->isValid()) {
                    $this->upload_image($request->file("image"), "image", $id);
                }
            }
            session()->flash('success', 'Festival added successfully!');
            return redirect()->route("festivals.index");
        }
    }

    public function festivals_status(Request $request)
    {
        $festivals = Festivals::find($request->get("id"));
        $festivals->status = ($request->get("checked") == "true") ? 1 : 0;
        $festivals->save();
    }

    public function festivals_feature_status(Request $request)
    {
        $post = FeaturePost::where("festival_id", $request->get("id"))->get();
        if ($post->isEmpty()) {
            FeaturePost::create([
                "festival_id" => $request->get("id"),
                "type" => "festival",
            ]);
            return 1;
        } else {
            FeaturePost::where("festival_id", $request->get("id"))->delete();
            return 0;
        }
    }

    public function edit($id)
    {
        $festivals = Festivals::find($id);
        return view("festivals.edit", compact("festivals"));
    }

    public function update(Request $request, $id)
    {
        $validation = Validator::make($request->all(), [
            "title" => 'required',
            "image" => "nullable|mimes:jpg,png,jpeg",
            "festivals_date" => 'required',
            "activation_date" => 'required',
        ]);

        if ($validation->fails()) {
            return back()->withErrors($validation)->withInput();
        } else {
            $festivals = Festivals::find($request->get("id"));
            $festivals->title = $request->get("title");
            $festivals->festivals_date = date_format(date_create(implode("", preg_split("/[-\s:,]/", $request->get("festivals_date")))), "Y-m-d");
            $festivals->activation_date = date_format(date_create(implode("", preg_split("/[-\s:,]/", $request->get("activation_date")))), "Y-m-d");
            $festivals->save();

            if (StorageSetting::getStorageSetting("storage") == "DigitalOcean") {
                if ($request->file("image") && $request->file('image')->isValid()) {
                    $image = $request->file('image');
                    $file = Str::uuid() . '.' . $image->getClientOriginalExtension();

                    $path = Storage::disk('spaces')->put('uploads/' . $file, file_get_contents($image), 'public');

                    $f = Festivals::find($request->get("id"));
                    $f->image = $file;
                    $f->save();
                }
            } else {
                if ($request->file("image") && $request->file('image')->isValid()) {
                    $this->upload_image($request->file("image"), "image", $id);
                }
            }
            session()->flash('success', 'Festival updated successfully!');
            return redirect()->route('festivals.index');
        }
    }

    public function festivals_search(Request $request)
    {
        $from_date = !empty($request->from_date) ? $request->from_date : '';
        $end_date = !empty($request->to_date) ? $request->to_date : '';

        $index['data'] = Festivals::where("title", 'LIKE', '%' . $request->search . '%')
            ->where(function ($query) use ($from_date, $end_date) {
                if (!empty($from_date)) {
                    $query->where('festivals_date', '>=', $from_date);
                }
                if (!empty($end_date)) {
                    $query->where('festivals_date', '<=', $end_date);
                }
            })->paginate(12);

        $index['festival'] = Festivals::get();
        $index['name'] = $request->search;
        return view("festivals.index", $index);
    }

    public function destroy($id)
    {
        $festivals = Festivals::find($id);
        $festivalsFrame = FestivalsFrame::where('festivals_id', $id)->get();
        $story = Story::where("festival_id", $id)->get();
        $video = Video::where("festival_id", $id)->get();

        if (StorageSetting::getStorageSetting("storage") == "DigitalOcean") {
            Storage::disk('spaces')->delete('uploads/' . $festivals->image);
            foreach ($festivalsFrame as $frame) {
                Storage::disk('spaces')->delete('uploads/' . $frame->frame_image);
            }
            foreach ($story as $s) {
                Storage::disk('spaces')->delete('uploads/' . $s->image);
            }
            foreach ($video as $v) {
                Storage::disk('spaces')->delete('uploads/video/' . $v->video);
            }
        } else {
             try{
                    unlink(base_path('uploads/') . $festivals->image);
                }catch(\Exception $e){
                
                }
            
            foreach ($festivalsFrame as $frame) {
                try{
                    unlink(base_path('uploads/') . $frame->frame_image);
                }catch(\Exception $e){
                    
                }
            }
            foreach ($story as $s) {
                try{
                    unlink(base_path('uploads/') . $s->image);
                }catch(\Exception $e){
                
                }
                
            }
            foreach ($video as $v) {
                 try{
                    unlink(base_path('uploads/video/') . $v->video);
                }catch(\Exception $e){
                
                }                
            }
        }
        session()->flash('success', 'Festival deleted successfully!');
        Festivals::find($id)->delete();
        FestivalsFrame::where('festivals_id', $id)->delete();
        FeaturePost::where('festival_id', $id)->delete();
        Story::where("festival_id", $id)->delete();
        Video::where("festival_id", $id)->delete();

        return redirect()->route('festivals.index');
    }

    private function upload_image($file, $field, $id)
    {
        $destinationPath = base_path('uploads/festival');
        $extension = $file->getClientOriginalExtension();
        $fileName = Str::uuid() . '.' . $extension;
        $file->move($destinationPath, $fileName);

        $image = Festivals::find($id);
        $image->$field = 'festival/' . $fileName;
        $image->save();
    }
}
