<?php

namespace App\Http\Controllers\Dashboard;

use App\Helpers\Alert;
use App\Http\Requests\Dashboard\NewDepartmentRequest;
use App\Http\Requests\Dashboard\UpdateDepartmentRequest;
use App\Models\Department;
use App\Models\File;
use App\Models\Folder;
use App\Models\User;
use App\Notifications\NewDepartmentCreated;
use App\Notifications\NewFolderCreated;
use Carbon\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Filesystem\Filesystem;

class DepartmentsController extends Controller
{
    public function index()
    {
        return view("dashboard.departments.index")->with([
            "departments" => Department::all()
        ]);
    }

    public function store(NewDepartmentRequest $request)
    {
        $department = new Department();

        $department->name = $request->name;
        $department->code = $request->code;

        $location = 'Departments' . DIRECTORY_SEPARATOR . $request->code;

        if(!Storage::disk('local')->has($location)){
            Storage::disk('local')->makeDirectory($location);

        }
        $department->location = $location;
        $department->user_id = auth()->id();

        $department->save();

        Alert::flash("New Department added successfully");

        return redirect()->route("dashboard.departments.index");
    }

    public function edit(UpdateDepartmentRequest $request, $id)
    {
        $department = Department::findOrFail($id);

        $folders = $department->folder;
        $oldLocation = DIRECTORY_SEPARATOR . 'Departments' . DIRECTORY_SEPARATOR . $department->code;

        $department->name = $request->name;
        $department->code = $request->code;
        $department->updated_at = Carbon::now();

        if($department->isDirty('code'))
        {
            $location = 'Departments' . DIRECTORY_SEPARATOR . $request->code;

            if(!Storage::disk('local')->has($location) ){
                Storage::disk('local')->move($oldLocation, $location);
                $department->location = $location;
            }

            foreach ($folders as $folder) {
                    $currArchId = explode('/', $folder->arch_id)[1];
                    $folder->arch_id = $department->code . '/' . $currArchId;
                    $folder->save();

                foreach($folder->files as $file) {
                    //dd($file);
                    $file->location = $location . DIRECTORY_SEPARATOR . $folder->name . DIRECTORY_SEPARATOR . $file->name;
                    $file->save();
                }
            }
        }

        $department->save();

        Alert::flash("Department edited successfully");

        return redirect()->route("dashboard.departments.index");
    }

    public function destroy($id)
    {
        $department = Department::find($id);
        //$department->delete();
        $folders = $department->folder()->count();

        if($folders > 0){
            Alert::flash($department->name . " has " . $folders . " document/s associated", "error");
        }
        else {
            $department->delete();

            Alert::flash($department->name . " deleted successfully");
        }

        return redirect()->route("dashboard.departments.index");
    }

    public function downloadAll()
    {
        $departments = Department::all();
        $flag=false;

        foreach ($departments as $department) {
                if($department->no_of_folders > 0) {
                    $folders = Folder::where('department_id', $department->id)->get();
                }
                foreach ($folders as $folder){
                    if($folder->no_of_files > 0){
                        $flag=true;
                        break;
                    }
                }
        }

            if($flag) {
            $zip_file = Storage::disk('local')->path('Departments.zip');
            $zip = new \ZipArchive();
            $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

            $path = Storage::disk('local')->path('Departments');

            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));

            foreach ($files as $file) {

                // We're skipping all subfolders
                if (!$file->isDir()) {
                    $filePath = $file->getRealPath();
                    // extracting filename with substr/strlen
                    $relativePath = substr($filePath, strlen($path) + 1);
                    $zip->addFile($filePath, $relativePath);
                }
            }
            $zip->close();
            $headers = array('Content-Type' => 'application/octet-stream');
            $zip_new_name = Carbon::now()->format('d.m.Y - ') . 'Departments.zip';
            return response()->download($zip_file, $zip_new_name, $headers);
                }

            else {
            Alert::flash("All folders are empty", "warning");
            return redirect()->back();
            }

    }

    public function downloadDepartment($id)
    {
            $department = Department::find($id);
            $folders = Folder::where('department_id', $id)->get();
            $flag = false;

            foreach($folders as $folder){
                if($folder->no_of_files > 0)
                    $flag=true;
                    break;
            }

            if($flag) {
            $zip_file=Storage::disk('local')->path('Department.zip');
            $zip = new \ZipArchive();
            $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
            $path = Storage::disk('local')->path($department->location);

            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));

            foreach ($files as $file) {

                // We're skipping all subfolders
                if (!$file->isDir()) {
                    $filePath = $file->getRealPath();
                    // extracting filename with substr/strlen
                    $relativePath = substr($filePath, strlen($path) + 1);
                    $zip->addFile($filePath, $relativePath);
                }
            }

            $zip->close();
            $headers = array('Content-Type' => 'application/octet-stream');
            $zip_new_name = Carbon::now()->format('d.m.Y - ') . $department->name . '.zip';
            return response()->download($zip_file, $zip_new_name, $headers);
                }
            else {
                Alert::flash("This department has no files", "warning");
                return redirect()->back();
            }
    }
}
