<?php

namespace App\Http\Controllers\Admin\Pages\Projects;

use App\Http\Controllers\Controller;
use App\Http\Requests\Projects\ProjectStoreRequest;
use App\Http\Requests\Projects\ProjectUpdateRequest;
use App\Models\PortCategory;
use App\Models\Project;
use App\Models\ProjectGallery;
use App\Traits\Description;
use App\Traits\FileUploader;
use App\Traits\ImageCompressor;
use App\Traits\Slug;
use App\Traits\Title;
use DataTables;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\File;


class ProjectController extends Controller
{

    use ImageCompressor ,FileUploader,Slug ,Title,Description;

    public function __construct()
    {
        $this->middleware('permission:view projects')->only('index', 'ajax');
        $this->middleware('permission:create project')->only('create');
        $this->middleware('permission:store project')->only('store');
        $this->middleware('permission:edit project')->only('edit');
        $this->middleware('permission:update project')->only('update');
        $this->middleware('permission:destroy project')->only('destroy');
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $projectCategories =PortCategory::all();
        return view('app.admin.pages.projects.all-project',compact([
            'projectCategories'
        ]));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $projectCategories = PortCategory::pluck('port_category', 'id');
        return view('app.admin.pages.projects.create-project', compact('projectCategories'));
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(ProjectStoreRequest $request)
    {
        try {
            $validatedData = $request->validated();

            if ($request->hasFile('image')) {
                $validatedData['image'] = self::compressImage($request->file('image'), 'ProjectImage');
            }


            $category_id = $request->input('category_id');

            $validatedData['category_id'] = $category_id;

            $project=Project::create($validatedData);

            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    ProjectGallery::create([
                        'project_id' => $project->id,
                        'partners' => self::compressImage($image, 'ProjectGallery')
                    ]);
                }
            }

            return back()->with('success', __('Data successfully created!'));
        } catch (\Exception $e) {
            return back()->withErrors([$e->getMessage()]);
        }
    }



    /**
     * Display the specified resource.
     */
    public function show(Project $project)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Project $project)
    {
        $projectCategories = PortCategory::pluck('port_category', 'id');
        return view('app.admin.pages.projects.edit-project', compact(
            'projectCategories',
            'project',
        ));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ProjectUpdateRequest $request, Project $project)
    {
        $validatedData = $request->safe();
        try {

            if ($request->hasFile('image')) {
                File::delete('/storage/images/' . $project->getAttribute('image'));
                $validatedData['image'] = self::compressImage($request->file('image'), 'ProjectImage');
            } else {
                $validatedData['image'] = $project->getAttribute('image');
            }




            $project->update($validatedData->except('partners'));

            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    ProjectGallery::create([
                        'project_id' => $project->id,
                        'partners' => self::compressImage($image, 'ProjectImage')
                    ]);
                }
            }

            return back()->with('success', __('Data successfully updated!'));
        } catch (Exception $e) {
            return back()->withErrors([$e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $project=Project::find($id);
            $project->delete();
            $project->gallery()->delete();
            return back()->with('success', __('Data successfully deleted!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * @return JsonResponse
     * @throws Exception
     */
    public function ajax()
    {
        $projects = Project::query();
        return DataTables::of($projects)->editColumn('image', function (Project $projects) {
            return view('app.admin.includes.table-elements.image', [
                'image' => $projects->image()
            ]);
        })->addColumn('options', function (Project $project) {
            return view('app.admin.includes.table-elements.action-buttons', [
                'modelName' => 'project',
                'editUrl' => route('admin:projects.edit', $project->getAttribute('id')),
                'deleteUrl' => route('admin:projects.destroy', $project->getAttribute('id'))
            ]);
        })->toJson();
    }
}
