<?php

namespace App\Http\Controllers\Api;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Owner\StoreOwnerRequest;
use App\Http\Requests\Owner\UpdateOwnerRequest;
use App\Http\Resources\OwnerResource;
use App\Models\Owner;
use App\Traits\CanManageFile;
use Spatie\QueryBuilder\QueryBuilder;

class OwnerController extends Controller
{
    use CanManageFile;

    public function __construct() {
        $this->resourceName = "owners";
        $this->fileFieldNames = ["aadhaar_card", "pan_card"];
        $this->fileFolderPaths = ["aadhaar-cards", "pan-cards"];
    }

    public function index() {
        $query = QueryBuilder::for(Owner::class)
            ->allowedFilters(['society_id', 'name', 'email', 'phone'])
            ->allowedIncludes(['society'])
            ->latest();

        $owners = $query
            ->paginate(request("perPage", 15));

        return ApiResponse::paginated($owners);
    }

    public function store(StoreOwnerRequest $request) {
        $owner = new Owner($request->validated());
        $this->storeFiles($request, $owner);
        $owner->save();

        return ApiResponse::created(
            new OwnerResource($owner),
            "Owner has been created successfully!"
        );
    }

    public function show(Owner $owner) {

        return ApiResponse::resource(new OwnerResource($owner));
    }

    public function update(UpdateOwnerRequest $request, Owner $owner) {
        $owner->fill($request->validated());
        $this->updateFiles($request, $owner);
        $owner->save();

        return ApiResponse::updated(
            new OwnerResource($owner),
            "Owner has been updated successfully!"
        );
    }

    public function destroy(Owner $owner) {
        $this->deleteFiles($owner);
        $owner->delete();

        return ApiResponse::deleted("Owner has been deleted successfully!");
    }
}
