<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use Illuminate\Http\Request;
// Import the Form Request classes
use App\Http\Requests\StoreProjectRequest;
use App\Http\Requests\UpdateProjectRequest;

class ProjectController extends BaseApiController
{
    /**
     * Display a listing of the projects.
     */
    public function index()
    {
        $projects = Project::with('Landloard')->get(); // Eager load Landloard relationship
        return $this->success([
            'projects' => ProjectResource::collection($projects),
        ], 'Projects retrieved successfully.');
    }

    /**
     * Store a newly created project in storage.
     */
    public function store(StoreProjectRequest $request) // <-- Use the Form Request
    {
        // The request is automatically validated before this method is called.
        // If validation fails, a 422 JSON response is returned automatically.
        $project = Project::create($request->validated()); // Use validated() to get the data

        return $this->success(new ProjectResource($project), 'Project created successfully.', 201);
    }

    /**
     * Display the specified project.
     */
    public function show(Project $project)
    {
        $project->load('Landloard');
        return $this->success(new ProjectResource($project), 'Project retrieved successfully.');
    }

    /**
     * Update the specified project in storage.
     */
    public function update(UpdateProjectRequest $request, Project $project) // <-- Use the Form Request
    {
        // Again, validation is handled automatically.
        $project->update($request->validated()); // Use validated() to get the data

        return $this->success(new ProjectResource($project), 'Project updated successfully.');
    }

    /**
     * Remove the specified project from storage.
     */
    public function destroy(Project $project)
    {
        $project->delete();
        return $this->success(null, 'Project deleted successfully.');
    }
}