<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\Department;
use App\Models\Employee;
use App\Models\In_Charge;
use App\Models\Story;
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->story_expiry();

            $params['in_charge'] = In_Charge::where('department_id', '!=', 0)->where('status', 1)->orderby('full_name', 'asc')->get();

            $input_search = $request['input_search'];
            $input_in_charge = $request['input_in_charge'];

            $query = Story::query();

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

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

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

            $this->common->imageNameToUrl($params['data'], 'story_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['in_charge'] = In_Charge::where('department_id', '!=', 0)->where('status', 1)->orderby('full_name', 'asc')->with('department')->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(), [
                'in_charge_id' => 'required',
                '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));
            }

            $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['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) {

                $params['in_charge'] = In_Charge::where('department_id', '!=', 0)->where('status', 1)->orderby('full_name', 'asc')->with('department')->get();

                if ($params['data']['type'] == 1) {
                    $this->common->imageNameToUrl(array($params['data']), 'story_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(), [
                'in_charge_id' => 'required',
                '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()));
        }
    }

    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"}');
    }
}
