<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Radio;

class RadioController extends BaseController
{
    public function getRadioList(Request $request) {
        try {
            $itemsPerPage = min((int) $request->input('per_page', 10), 100);
            $currentPage = $request->input('page', 1);

            $radios = Radio::with('category')->where('status', 0)->orderBy('created_at', 'desc')->paginate($itemsPerPage, ['*'], 'page', $currentPage); 

            if ($radios->isEmpty()) {
                return $this->formatPaginatedResponse([], 'No radio list found', $currentPage, $itemsPerPage, $radios->total());
            }

            return $this->formatPaginatedResponse($radios->items(), 'Radio list retrieved successfully', $currentPage, $itemsPerPage, $radios->total());

        }catch(\Exception $e){
            return $this->handleException($e);
        }
 
    }

    public function getRadioById($id)
    {
        try {
            $radio = Radio::with('category')->findOrFail($id);

            return $this->formatResponse($radio, 'Radio retrieved successfully');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    public function getRadioListByCategoryId(Request $request, $categoryId)
    {
        try {
            $itemsPerPage = min((int) $request->input('per_page', 10), 100);
            $currentPage = $request->input('page', 1);

            $radios = Radio::with('category')
                ->where('status', 0)
                ->where('radio_category_id', $categoryId)
                ->orderBy('created_at', 'desc')
                ->paginate($itemsPerPage, ['*'], 'page', $currentPage);

            if ($radios->isEmpty()) {
                return $this->formatPaginatedResponse([], 'No radio found', $currentPage, $itemsPerPage, $radios->total());
            }

            return $this->formatPaginatedResponse($radios->items(), 'Radio list retrieved successfully', $currentPage, $itemsPerPage, $radios->total());

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    public function incrementViewCount($id)
    {
        try {
            $radio = Radio::findOrFail($id);
            $radio->increment('total_views');
            
            return $this->formatResponse(null, 'View count incremented successfully');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }
}
