<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Models\User;
use App\Models\CabinClass;
use App\Models\Company;
use App\Models\Product;
use App\Models\Folder;
use App\Models\Document;

class FileController extends Controller
{
    public $local_store;

    public function __construct()
    {
        //
        $this->local_store = 'fake_s3';
        
        $this->middleware('auth:api');

        $api_user = auth()->guard('api')->user();

        if (!$api_user)
        {
            return response()->json(['error' => 'Unauthorized.'], 401);
        }

    }

    public function index(Request $request) {

        $user = auth()->guard('api')->user();
        $company = Company::where('id', $user->company_id)->first();
        $companyFolder = Folder::where('id', $company->folder_id)->first();

        $items = [];

        $dirs = Storage::disk($this->local_store)->directories($companyFolder->path);
        $files = Storage::disk($this->local_store)->files($companyFolder->path);

        foreach ($dirs as $index => $dir) {
            $folder = Folder::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)))->first();

            if (!$folder)
            {
                $folder = Folder::create(['path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir))]);
            }

            array_push($items, [
                'name' => basename($dir),
                'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)),
                'folder_id' => $folder->id,
                'type' => 'folder'
            ]);

        }

        foreach ($files as $index => $file) {
            array_push($items, [
                'name' => basename($file),
                'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)),
                'type' => 'file'
            ]);
        }

        $res = [
            'parent' => '/',
            'items' => $items
        ];

        return response()->json(['parent' => '/', 'items' => $items]);

    }
    public function showById($id, Request $request) {

        $user = auth()->guard('api')->user();
        $items = [];

        $folder = Folder::find($id);
        if (!$folder) {
            return response()->json(['error' => 'Folder not found'], 404);
        }

        $path = $folder->path;

        $dirs = Storage::disk($this->local_store)->directories($folder->path);
        $files = Storage::disk($this->local_store)->files($folder->path);


        foreach ($dirs as $index => $dir) {

            $sub_files = Storage::disk($this->local_store)->files($dir);

            if ($sub_files) {
                foreach ($sub_files as $k => $v){ 
                    if ( count(explode("/", $v)) == 4 ) {
                        $files[] = $v;
                    }
                }
            }

            if (!$sub_files || count( explode("/", $dir) ) <= 2 ) {

                $folderPath = $this->pathFromUrl(Storage::disk($this->local_store)->url($dir));

                $folder_expl = explode("/", $folderPath);

                // if (count($folder_expl) == 3) {
                //     $folderPath = $folder_expl[0]."/".$folder_expl[1];
                // }

                $subdir = Folder::where('path', $folderPath)->first();
                # die();

                if (!$subdir) {
                    return response()->json(['error' => config('app.url')], 500);
                }

                $subdir->path = $dir;

                 #var_dump($folderPath);
                 #var_dump($subdir->path);
                 #var_dump($this->pathFromUrl(Storage::disk($this->local_store)->url($dir)));

                array_push($items, [
                    'name' => basename($dir),
                    'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)),
                    'folder_id' => $subdir->id,
                    'type' => 'folder'
                ]);
            }
        }
        #die('ok');

        #var_dump($items);
        #var_dump($files);die();

        foreach ($files as $index => $file) {
            $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($file)))->first();
            $serial = '';

            if ($document) {
                $product = $document->product;
                $serial = $product ? $product->serial_number : '';
            }
            # var_dump($this->pathFromUrl(Storage::disk($this->local_store)->url($file)));

            $path_expl = explode("/", $file);

            if (count($path_expl) == 4 ) {

                array_push($items, [
                    'name' => $path_expl[2]."/".basename($file),
                    'sub_folder' => $path_expl[2],
                    'name' => ($document->name != null ? $document->name : $this->pathFromUrl(Storage::disk($this->local_store)->url($file)) ),
                    'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)),
                    'serial_number' => $serial,
                    'type' => 'file'
                ]);

            }else{
                array_push($items, [
                    'name' => basename($file),
                    'sub_folder' => '',
                    'name' => ($document->name != null ? $document->name : $this->pathFromUrl(Storage::disk($this->local_store)->url($file)) ),
                    'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)),
                    'serial_number' => $serial,
                    'type' => 'file'
                ]);
            }

        }

        return response()->json(['parent' => $path, 'parent_id' => $folder->parent_id, 'company_id' => $folder->company_id, 'items' => $items]);


    }
    public function showByIdDEPRECATED($id, Request $request) {

        $user = auth()->guard('api')->user();
        $company = Company::where('id', $user->company_id)->first();
        $companyFolder = Folder::where('id', $company->folder_id)->first();

        $items = [];

        $folder = Folder::find($id);

        if (!$folder) {
            return response()->json(['error' => 'Folder not found'], 404);
        } else if ($folder->company_id != $company->id) {
            return response()->json(['error' => 'Permission denied'], 403);
        }

        $path = $folder->path;
        $path_arr = explode('/', $path);
        $cabin = CabinClass::where('name', end($path_arr));

        $dirs = Storage::disk($this->local_store)->directories($folder->path);
        $files = Storage::disk($this->local_store)->files($folder->path);

        if (!$cabin) {
            return response()->json(['error' => 'Permission denied.'], 403);
        }

        foreach ($dirs as $index => $dir) {
            $folderPath = $this->pathFromUrl(Storage::disk($this->local_store)->url($dir));
            $subdir = Folder::where('path', $folderPath)->first();

            if (!$subdir) {
                return response()->json(['error' => 'Folder not found'], 500);
            }

            array_push($items, [
                'name' => basename($dir),
                'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)),
                'folder_id' => $subdir->id,
                'type' => 'folder'
            ]);
        }

        foreach ($files as $index => $file) {
            $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($file)))->first();
            if ($document) {
                $product = $document->product;
                $serial = $product ? $product->serial_number : '';
            }

            array_push($items, [
                'name' => basename($file),
                'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)),
                'serial_number' => $serial,
                'type' => 'file'
            ]);
        }

        return response()->json(['parent' => $path, 'parent_id' => $folder->parent_id, 'items' => $items]);

    }

    public function download(Request $request) {
        $user = auth()->guard('api')->user();
        $company = Company::where('id', $user->company_id)->first();

        return Storage::disk($this->local_store)->download('\/'.$request->path);
    }

    protected function pathFromUrl($path) {
        $path = str_replace(config('app.url'), '', $path);
        $path = str_replace('storage/', '', $path);
        $path = trim($path, '/');
        return $path;
    }

}
