<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Http\Requests\ChapterRequest;
use App\Models\Chapter;
use App\Models\Law;
use App\Models\Order;
use App\Traits\BaseApiResponse;

class ChapterController extends Controller
{
    use BaseApiResponse;

    public function index(ChapterRequest $request)
    {
        $validated = $request->validated();

        $perPage = $validated['per_page'] ?? 15;
        $page = $validated['page'] ?? 1;

        $chapters = Chapter::where('book_id' , $validated['book_id'])->paginate($perPage, ['*'], 'page', $page);

        $chapters->getCollection()->transform(function ($section) {

            $section['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $section['law_id'])->first()?->is_locked;

            unset($section['law_id']);
            unset($section['section_id']);

            return $section;
        });

        return $this->success($chapters->items());
    }
}
