<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\RequestAssignmentResouce;
use App\Models\PbgTask;
use App\Models\PbgTaskGoogleSheet;
use DB;
use Exception;
use Illuminate\Http\Request;
use Log;

class RequestAssignmentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = PbgTask::query()->orderBy('id', 'desc');
        if($request->has('search') && !empty($request->get("search"))){
            $query->where('name', 'LIKE', '%'.$request->get('search').'%')
            ->orWhere('registration_number', 'LIKE', '%'.$request->get('search').'%')
            ->orWhere('document_number', 'LIKE', '%'.$request->get('search').'%');
        }
        return RequestAssignmentResouce::collection($query->paginate());
    }

    public function report_payment_recaps(Request $request)
    {
        try {
            // Query dengan group by kecamatan dan sum nilai_retribusi_keseluruhan_simbg
            $query = PbgTaskGoogleSheet::select(
                    'kecamatan',
                    DB::raw('SUM(nilai_retribusi_keseluruhan_simbg) as total')
                )
                ->groupBy('kecamatan')
                ->paginate(10);

            // Return hasil dalam JSON format
            return response()->json([
                'success' => true,
                'data' => $query
            ]);

        } catch (Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['message' => 'Terjadi kesalahan: ' . $e->getMessage()], 500);
        }
    }
    public function report_pbg_ptsp()
    {
        try {
            // Query dengan group by status dan count total per status
            $query = PbgTask::select(
                    'status',
                    'status_name',
                    DB::raw('COUNT(*) as total')
                )
                ->groupBy('status', 'status_name')
                ->paginate(10);

            // Return hasil dalam JSON format
            return response()->json([
                'success' => true,
                'data' => $query
            ]);

        } catch (Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['message' => 'Terjadi kesalahan: ' . $e->getMessage()], 500);
        }
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
