<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Http\Models\FileVideoModel;
use App\Http\Models\FolderModel;
use DateTime;
use Redirect;
use View;
use Auth;
use Validator;
use ZipArchive;

class VideoController extends Controller
{
    public function index()
    {
        $folder = FolderModel::where('folder_type', 1)
            ->orderBy('id', 'DESC')
            ->get();

        $data = FileVideoModel::where('folder_id', '=', null)->orderBy('id', 'DESC')->paginate(100);
        $urlsVideo = $data->map(function ($fileObj) {
            return [
                'id' => $fileObj->id,
                'url' => env('R2_SCHEMA_URL') . $fileObj->name,
                'name' => $fileObj->name,
                'created_at' => $fileObj->created_at,
            ];
        });

        return View::make("backend/video/index")
            ->with('folderView', $folder)
            ->with('itemView', $urlsVideo);
    }

    public function folder($folderId)
    {
        $folder = FolderModel::where('id', $folderId)->first();
        $data = FileVideoModel::where('folder_id', $folderId)
            ->orderBy('id', 'DESC')
            ->paginate(100);

        $urls = $data->map(function ($fileObj) {
            return [
                'id' => $fileObj->id,
                'url' => env('R2_SCHEMA_URL') . $fileObj->name,
                'name' => $fileObj->name,
                'created_at' => $fileObj->created_at,
            ];
        });

        return View::make("backend/video/folder/index")
            ->with('folderView', $folder)
            ->with('itemView', $urls);
    }

    public function add($folderId = null)
    {
        return View::make("backend/video/add")
            ->with('folderIdView', $folderId);
    }

    public function insert(Request $request)
    {
        $validated = $request->validate([
            'fileName' => 'required|string'
        ]);

        // prepared data
        $folderId = $request->input('folderId');
        $data = [
            'folder_id' => null,
            'user_id' => Auth::user()->id,
            'name' => $validated['fileName'],
            'created_at' => new DateTime(),
        ];
        // If $folderId is not null, add it to the $data array
        if ($folderId !== null) {
            $data['folder_id'] = $folderId;
        }

        $id = FileVideoModel::insertGetId($data);

        // insert to database
        if ($id > 0) { // insert success then return ID
            return response()->json(['message' => 'File name saved successfully'], 200);
        } else { // insert fail
            return response()->json(['message' => 'Failed to save file name'], 500);
        }
    }

    public function edit($id)
    {
        // get by id
        $data = FileVideoModel::where('id', $id)->first();

        if (is_null($data)) { // not found
            return Redirect::to("video")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        return View::make('backend/video/edit')
            ->with('idView', $id)
            ->with('itemView', $data);
    }

    public function view($id)
    {
        // get by id
        $data = FileVideoModel::where('id', $id)->first();

        if (is_null($data)) { // not found
            return Redirect::to("video")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        return View::make('backend/video/view')
            ->with('idView', $id)
            ->with('itemView', $data);
    }

    public function update(Request $request)
    {
        // keep data en
        $id = $request->input('id');

        // redirect with message
        return Redirect::to("video")
            ->withInput()
            ->with("messageSuccess", "Success")
            ->with("messageDetail", 'Updated success');
    }

    public function delete(Request $request)
    {
        $id = $request->input('item_id');
        FileVideoModel::where('id', '=', $id)->delete();
        return response()->json([
            'status' => true,
            'message' => "Deleted success"
        ]);
    }


    // Folder
    public function addFolder()
    {
        return View::make("backend/video/folder/add");
    }

    public function insertFolder(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string'
        ]);

        // exist folder name
        $exist = FolderModel::where('name', $validated['name'])
            ->where('folder_type', 1)
            ->first();

        if ($exist != null) {
            return Redirect::to("video")
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Folder already exist');
        }


        // prepared data
        $data = [
            'name' => $validated['name'],
            'folder_type' => 1,
            'created_at' => new DateTime(),
        ];
        $id = FolderModel::insertGetId($data);

        // insert to database
        if ($id > 0) { // insert success then return ID
            return Redirect::to("video")
                ->withInput()
                ->with("messageSuccess", "Success")
                ->with("messageDetail", 'Create folder success');
        } else { // insert fail
            return Redirect::to("video")
                ->withInput()
                ->with("messageSuccess", "Fail")
                ->with("messageDetail", 'Create folder unsuccess');
        }
    }

    public function editFolder($id)
    {
        // get by id
        $data = FolderModel::where('id', $id)
            ->first();
        if (is_null($data)) { // not found
            return Redirect::to("video/folder/" . $id)
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Not found data');
        }

        return View::make('backend/video/folder/edit')
            ->with('idView', $id)
            ->with('itemView', $data);
    }

    public function updateFolder(Request $request)
    {
        // keep data en
        $id = $request->input('id');
        $name = $request->input('name');

        // validate
        $validator = Validator::make($request->all(), [
            'name' => 'required'
        ]);

        if ($validator->fails()) {
            return Redirect::to("video/folder/" . $id)
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Data can not be empty');
        }

        // check existing
        $exist = FolderModel::where('id', '!=', $id)
            ->where('folder_type', 1)
            ->where('name', $name)
            ->count();
        if (
            $exist > 0
        ) {
            return Redirect::to("video/edit-folder/" . $id)
                ->withInput()
                ->with("messageFail", "Fail")
                ->with("messageDetail", 'Name already exist');
        }

        $data = [
            'name' => $name,
        ];

        FolderModel::where('id', $id)->update($data);

        return Redirect::to("video")
            ->with("messageSuccess", "Success")
            ->with("messageDetail", 'Updated success');
    }

    public function deleteFolder(Request $request)
    {
        $id = $request->input('item_id');
        $hasFilesInFolder =  FileVideoModel::where('folder_id', $id)->count();
        if ($hasFilesInFolder > 0) { // not found
            return response()->json([
                'status' => false,
                'message' => "Can not delete already in folder"
            ]);
        } else {

            // delete user in database
            FolderModel::where('id', '=', $id)->delete();
            return response()->json([
                'status' => true,
                'message' => "Delete successfully"
            ]);
        }
    }

    public function downloadFolder($folderId)
    {
        $files = FileVideoModel::where('folder_id', $folderId)->get(); 
        $zip = new ZipArchive;
        $folder = FolderModel::where('id', $folderId)->first();
        $zipFileName = $folder->name . '.zip';
        $zipPath = storage_path('app/' . $zipFileName);

        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
            foreach ($files as $file) {
                $filePath = env('R2_SCHEMA_URL') . $file->name;
                $fileContents = file_get_contents($filePath); // Download each file from R2
                $zip->addFromString($file->name, $fileContents);
            }
            $zip->close();
        }

        return response()->download($zipPath)->deleteFileAfterSend(true);
    }
}
