<?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\User;
use App\Notifications\NewDepartmentCreated;
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 create()
    {
        return view("dashboard.departments.create");
    }

    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('uploads')->has($location)){
            Storage::disk('uploads')->makeDirectory($location);

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

        $users = User::all();
        Notification::send($users, new NewDepartmentCreated("New department created"));

        $department->save();

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

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

    public function editShow($id)
    {
        return view("dashboard.departments.edit")->with([
            "department" => Department::findOrFail($id)
        ]);
    }

    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('uploads')->has($location)){
                Storage::disk('uploads')->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) {
                    $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()
    {
        $zip_file=Storage::disk('uploads')->path('Departments.zip');
        $zip = new \ZipArchive();
        $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $path = Storage::disk('uploads')->path('Departments');
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
        $flag=false;

        foreach ($files as $file)
        {
            if(File::all()->count() > 0) {

                // 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);
                }
            }
            else
            {
                $flag=true;
            break;
            }
        }
        if(!$flag) {
            $zip->close();
            $headers = array('Content-Type' => 'application/octet-stream');
            $zip_new_name = Carbon::now()->format('d.m.Y - H:i') . '- Departments.zip';
            return response()->download($zip_file, $zip_new_name, $headers);
        }
        else {
            Alert::flash("All departments are empty", "warning");
            return redirect()->back();
        }
    }

    public function downloadDepartment($id)
    {
        $department = Department::find($id);

        $FileSystem = new Filesystem();
        $zip_file = Storage::disk('uploads')->path('Department.zip');
        $zip = new \ZipArchive();
        $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $path = Storage::disk('uploads')->path($department->location) . DIRECTORY_SEPARATOR;
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));

        $filesInDept = $FileSystem->allFiles($path);

        if(!empty($filesInDept)) {
        foreach ($files as $file) {
            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 - H:i') . $department->name . '.zip';
        return response()->download($zip_file, $zip_new_name, $headers);
        }
        else{
            Alert::flash("This department has no files", "warning");
            return redirect()->back();
        }

    }
}
