<?php

namespace App\Http\Controllers;

use App\Models\APIs\MonthlyReport;
use App\Http\Requests\StoreMonthlyReportRequest;
use App\Http\Requests\UpdateMonthlyReportRequest;
use Illuminate\Http\JsonResponse;

class MonthlyReportController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    // 🔍 GET all reports
    public function index(): JsonResponse
    {
        $reports = MonthlyReport::latest()->get();
        return response()->json($reports);
    }

     // 🟢 1. Fetch all Regions
    public function regions(): JsonResponse
    {
        $regions = array_keys(config('regions'));

        return response()->json([
            'regions' => $regions
        ]);
    }

    // 🟢 2. Fetch Provinces under a Region
    public function provinces(string $region): JsonResponse
    {
        $allRegions = config('regions');

        if (!isset($allRegions[$region])) {
            return response()->json([
                'error' => 'Region not found'
            ], 404);
        }

        return response()->json([
            'provinces' => $allRegions[$region]
        ]);
    }

    // 📝 POST create report
    public function store(StoreMonthlyReportRequest $request): JsonResponse
{
    $data = $request->validated();
    $data['created_date'] = now(); // Auto-generate current timestamp

    $report = MonthlyReport::create($data);

    return response()->json([
        'message' => 'Monthly report created successfully.',
        'data' => $report,
    ], 201);
}


    // 🔍 GET single report
    public function show(string $id): JsonResponse
    {
        $report = MonthlyReport::find($id);

        if (!$report) {
            return response()->json(['error' => 'Report not found'], 404);
        }

        return response()->json($report, 200);
    }

    // ✏️ PUT update report
    public function update(UpdateMonthlyReportRequest $request, string $id): JsonResponse
    {
        $report = MonthlyReport::find($id);

        if (!$report) {
            return response()->json(['error' => 'Report not found'], 404);
        }

        $report->update($request->validated());

        return response()->json([
            'message' => 'Monthly Report Updated',
            'data' => $report
        ], 200);
    }


    // ❌ DELETE report
    public function destroy(string $id): JsonResponse
{
    $report = MonthlyReport::find($id);

    if (!$report) {
        return response()->json(['error' => 'Report not found'], 404);
    }

    $report->delete();

    return response()->json(['message' => 'Monthly Report Deleted']);
}

}
