<?php

namespace App\Repositories;

use App\Repositories\Contracts\EmployeeRepository;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

class EloquentEmployeeRepository extends EloquentBaseRepository implements EmployeeRepository
{
    /**
     * Store a newly created resource in storage.
     *
     * @param $request
     * @return object
     */
    public function requestHandler($request)
    {
        DB::beginTransaction();
        if (isset($request['employee_image'])) {
            $request['employee_image'] = implode(', ', $this->employeeImageUploader($request));
        }
        DB::commit();

        return $request;
    }

    /**
     * Update Specific resource in storage.
     *
     * @param $employee
     * @param $request
     * @return object
     */
    public function updateRequestHandler($employee, $request)
    {
        DB::beginTransaction();
        if (isset($request['employee_image'])) {
            $employeeImagesArray = explode(',', str_replace(' ', '', $employee['employee_image']));
            $this->deleteImages($employeeImagesArray);
            $request['employee_image'] = implode(', ', $this->employeeImageUploader($request));
        }
        DB::commit();
        return $request;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param $employee
     * @return bool
     */
    public function deleteHandler($employee)
    {
        DB::beginTransaction();
        $employeeImagesArray = explode(',', str_replace(' ', '', $employee['employee_image']));
        $this->deleteImages($employeeImagesArray);
        $status = parent::delete($employee);
        DB::commit();
        if ($status === true){
            $status = response()->json(['status' => 200, 'message' => 'Resource has been deleted.']);
        }

        return $status;
    }

    /**
     * Employee images uploader.
     *
     * @param $request
     * @return array
     */
    public function employeeImageUploader($request)
    {
        $employeeImagesNames = [];
        foreach ($request['employee_image'] as $key => $employeeImage) {
            $newImage = 'employee-image'.time() .$key.'-'.$request['organization_id'].'-'.$request['herd_id'].'-'.$request['lot_id']. '.' . $employeeImage->extension();
            $employeeImage->move(public_path('employee-images'), $newImage);
            $employeeImagesNames[] = $newImage;
        }

        return $employeeImagesNames;
    }

    /**
     * Delete images.
     *
     * @param $employeeImagesArray
     */
    public function deleteImages($employeeImagesArray)
    {
        foreach ($employeeImagesArray as $employeeImages) {
            if (File::exists(public_path().'/employee-images/' . $employeeImages)) {
                File::delete(public_path().'/employee-images/' . $employeeImages);
            }
        }
    }
}
