<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Story;
use App\Models\Story_View;
use App\Models\User;
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->remove_story();

            $params['creator'] = User::where('is_creator', 1)->latest()->get();

            $input_search = $request['input_search'];
            $input_creator = $request['input_creator'];
            $input_date = $request['input_date'];

            $query = Story::query();

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

            if ($input_date != null && isset($input_date)) {
                $query->whereDate('created_at',  $input_date);
            }

            if ($input_creator != "all" && $input_creator != null) {
                $query->where('user_id', $input_creator);
            }

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

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

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

    public function create()
    {
        try {
            $params['creator'] = User::where('is_creator', 1)->latest()->get();

            return view('admin.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(), [
                'user_id' => 'required',
                'type' => 'required',
                'description' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            if ($request->type == "video") {
                $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));
            }

            $requestData = $request->all();
            if ($requestData['type'] == "video") {
                $requestData['url'] = $request->video;
            } else {
                $files = $requestData['image'];
                $requestData['url'] = $this->common->saveImage($files, $this->folder, "story_");
            }
            unset($requestData['video'], $requestData['image']);

            $requestData['total_view'] = 0;
            $requestData['status'] = 1;

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

                return response()->json(array('status' => 200, 'success' => __('Label.data_add_successfully')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.data_not_added')));
            }
        } 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['url']);
                Story_View::where('story_id', $id)->delete();
                $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) {

                $params['creator'] = User::where('is_creator', 1)->latest()->get();

                if ($params['data']['type'] == "image") {
                    $this->common->imageNameToUrl(array($params['data']), 'url', $this->folder);
                }
                return view('admin.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(), [
                'user_id' => 'required',
                'type' => 'required',
                'description' => 'required',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            if ($request->type == "video") {
                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 == "image") {
                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();
            if (isset($requestData['image']) && $requestData['type'] == 'image') {
                $files = $requestData['image'];
                $requestData['url'] = $this->common->saveImage($files, $this->folder, "story_");
                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_url']));
            }
            if ($requestData['video'] != null && $requestData['type'] == 'video') {
                $requestData['url'] = $request->video;
                $this->common->deleteImageToFolder($this->folder, basename($requestData['old_url']));
            }
            unset($requestData['video'], $requestData['image'], $requestData['old_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.data_add_successfully')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.data_not_added')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function changeStatus($id)
    {
        try {
            $data = Story::where('id', $id)->first();
            if ($data->status == 0) {
                $data->status = 1;
            } elseif ($data->status == 1) {
                $data->status = 0;
            } else {
                $data->status = 0;
            }
            $data->save();
            return response()->json(array('status' => 200, 'success' => __('Label.status_changed'), 'id' => $data->id, 'Status' => $data->status));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function SaveChunkStory()
    {
        @set_time_limit(5 * 60);

        $targetDir = base_path('storage/app/public/story');
        //$targetDir = 'uploads';

        $cleanupTargetDir = true; // Remove old files

        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $category_image = $fileName;
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $category_image;
        // Chunking might be enabled

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        // Remove old temp files

        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}.part") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file

        if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);
        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off
            rename("{$filePath}.part", $filePath);

            // Generate a new filename based on the current date and time
            $extension = pathinfo($fileName, PATHINFO_EXTENSION); // Get the file extension from the original filename
            $newFileName = 'story' . date('_d_m_Y_') . rand(1111, 9999) . '.' . $extension; // Use the extracted extension
            $newFilePath = $targetDir . DIRECTORY_SEPARATOR . $newFileName;

            // Rename the uploaded file to the new filename
            rename($filePath, $newFilePath);

            // Send the new file name back to the client
            die(json_encode(array('jsonrpc' => '2.0', 'result' => $newFileName, 'id' => 'id')));
        }
        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }
}
