<?php

namespace App\Http\Controllers\In_Charge;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Story;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Validator;

class StoryController extends Controller
{
    private $folder = "story";
    public $common;

    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {
            $this->common->story_expiry();

            $incharge = InCharge_Data();
            $input_search = $request['input_search'];

            $query = Story::where('in_charge_id', $incharge['id']);

            if ($input_search != null && isset($input_search)) {
                $query->where('description', 'LIKE', "%{$input_search}%");
            }

            $params['data'] = $query->orderBy('id', 'DESC')->paginate(15);

            $this->common->imageNameToUrl($params['data'], 'story_url', $this->folder);

            return view('incharge.story.index', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function create()
    {
        try {
            $params = [];
            return view('incharge.story.add', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'type' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            if ($request->type == "2") {
                $validator2 = Validator::make($request->all(), [
                    'video' => 'required',
                ]);
            } else {
                $validator2 = Validator::make($request->all(), [
                    'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
                ]);
            }
            if ($validator2->fails()) {
                $errs2 = $validator2->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs2));
            }

            $incharge = InCharge_Data();
            $requestData = $request->all();
            $requestData['description'] = isset($request->description) ? $request->description : "";
            if ($requestData['type'] == "2") {
                $requestData['story_url'] = $request->video;
            } else {
                $files = $requestData['image'];
                $requestData['story_url'] = $this->common->saveImage($files, $this->folder, "story_");
            }
            unset($requestData['video'], $requestData['image']);
            $requestData['in_charge_id'] = $incharge['id'];
            $requestData['status'] = 1;

            $story_data = Story::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($story_data->id)) {

                return response()->json(array('status' => 200, 'success' => __('label.success_add_postages')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('label.error_add_postages')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function show($id)
    {
        try {
            $data = Story::where('id', $id)->first();
            if (isset($data)) {

                $this->common->deleteImageToFolder($this->folder, $data['story_url']);
                $data->delete();
            }
            return redirect()->back()->with('success', __('label.data_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function edit($id)
    {
        try {

            $params['data'] = Story::where('id', $id)->first();
            if ($params['data'] != null) {

                if ($params['data']['type'] == 1) {
                    $this->common->imageNameToUrl(array($params['data']), 'story_url', $this->folder);
                }
                return view('incharge.story.edit', $params);
            } else {
                return redirect()->back()->with('error', __('label.page_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function update(Request $request, string $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'type' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            if ($request->type == "2") {
                if ($request->old_video_url == null) { // image to video change 
                    $validator2 = Validator::make($request->all(), [
                        'video' => 'required',
                    ]);
                    if ($validator2->fails()) {
                        $errs2 = $validator2->errors()->all();
                        return response()->json(array('status' => 400, 'errors' => $errs2));
                    }
                }
            } else if ($request->type == "1") {
                if ($request->old_image == null) { // on change to video to image 
                    $validator2 = Validator::make($request->all(), [
                        'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
                    ]);
                } else { // image save 
                    $validator2 = Validator::make($request->all(), [
                        'image' => 'image|mimes:jpeg,png,jpg|max:2048',
                    ]);
                }
                if ($validator2->fails()) {
                    $errs2 = $validator2->errors()->all();
                    return response()->json(array('status' => 400, 'errors' => $errs2));
                }
            }

            $requestData = $request->all();
            $requestData['description'] = isset($request->description) ? $request->description : "";
            if (isset($requestData['image']) && $requestData['type'] == '1') {
                $files = $requestData['image'];
                $requestData['story_url'] = $this->common->saveImage($files, $this->folder, "story_");
                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_story_url']));
            }
            if ($requestData['video'] != null && $requestData['type'] == '2') {
                $requestData['story_url'] = $request->video;
                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_story_url']));
            }
            unset($requestData['video'], $requestData['image'], $requestData['old_story_url'], $requestData['old_video_url'], $requestData['old_image']);

            $story_data = Story::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($story_data->id)) {

                return response()->json(array('status' => 200, 'success' => __('label.success_edit_postages')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('label.error_edit_postages')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
