<?php

namespace App\Modules\Company\Employees;
use App\Models\WorkerFile;
use App\Traits\ValidatorTraits;
use App\Modules\RemoteStorage\GoogleBucketGateway;
use App\Traits\GoogleBucket;


class File
{
    use ValidatorTraits, GoogleBucket;

    public $googleBucket;
    public function __construct(GoogleBucketGateway $googleBucket)
    {
        $this->googleBucket = $googleBucket;
    }

    public function update($payload, $id){
        $rules = array(
            'name' => 'required|max:200',
            'oldName' => 'required',
            'worker_id' => 'required',
        );
        $validate = $this->validateRequest($payload, $rules);
        if ($validate) {
            return $validate;
        }
        $newName = $payload->name;
        $oldName = $payload->oldName;
        $workerID = $payload->worker_id;

        if($oldName == $newName){
            return response()->json(['errors' => 'No changes detected.'])->setStatusCode(201);
        }

        $validateDuplicate = WorkerFile::where('name', $newName)
            ->where('worker_id', $workerID)
            ->first();

        if($validateDuplicate){
            return response()->json(['errors' => 'File with the same name already exist. Please rename it.'])->setStatusCode(201);
        }   

        $newFileData = array(
            'name' => $newName,
        );

        $updateTransaction = WorkerFile::where('id', $id)->update($newFileData);

        if($updateTransaction){
            return response()->json(['success' => 'Data updated successfully.'])->setStatusCode(201);
        }

        return response()->json(['errors' => 'Something went wrong while updating file data. Please try again later.'])->setStatusCode(201);
    }

    public function remove($payload, $id){

        $rules = array(
            'location' => 'required',
        );
        $validate = $this->validateRequest($payload, $rules);
        if ($validate) {
            return $validate;
        }

        if($payload->location){
            $this->removeUploadedFile($payload->location, $this->googleBucket); //remove the previous link
        }
        
        $removeTransaction = WorkerFile::where('id', $id)->delete();

        if($removeTransaction){
            return response()->json(['success' => 'Data deleted successfully.'])->setStatusCode(201);
        }
        return response()->json(['errors' => 'Something went wrong while deleting file data. Please try again later.'])->setStatusCode(201);
    }

}