<?php

namespace App\Http\Controllers;

use App\Models\FgmDetail;
use App\Models\FgmService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class FgmDataController extends Controller
{
    /**
     * Store FGM quarterly data and related service details.
     *
     * This intentionally runs inside a transaction because the main FGM record and
     * the service rows must be saved together. If any service row fails, the main
     * record is rolled back.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'fyear' => 'required|digits:4|integer|min:2016|max:' . date('Y'),
            'quarter' => 'required|integer|between:1,4',
            'number' => 'required|integer|min:0',
            'districtid' => 'required|integer|exists:districts,id',
            'subcountyid' => 'required|integer|exists:sub_counties,id',
            'parishid' => 'required|integer|exists:parishes,id',
            'village' => 'nullable|string|max:150',
        ]);

        DB::beginTransaction();

        try {
            $detail = new FgmDetail();
            $detail->fyear = $validated['fyear'];
            $detail->quarter = $validated['quarter'];
            $detail->number = $validated['number'];
            $detail->districtid = $validated['districtid'];
            $detail->subcountyid = $validated['subcountyid'];
            $detail->parishid = $validated['parishid'];
            $detail->village = $validated['village'] ?? null;

            if (\Schema::hasColumn($detail->getTable(), 'created_by')) {
                $detail->created_by = optional(Auth::user())->id;
            }

            $detail->saveOrFail();

            foreach ($request->all() as $key => $value) {
                if (strpos($key, 'service_') !== 0) {
                    continue;
                }

                $index = substr($key, strlen('service_'));
                $girls = (int) $request->input('girls_' . $index, 0);

                if ($girls < 0) {
                    throw new \InvalidArgumentException('Number of girls for a service cannot be negative.');
                }

                // Skip empty service rows instead of failing the whole form.
                if ($girls === 0) {
                    continue;
                }

                $service = new FgmService();
                $service->fgm_detail_id = $detail->id;
                $service->service_id = (int) $value;
                $service->number = $girls;
                $service->saveOrFail();
            }

            DB::commit();

            return redirect(url('/dataentry/fgm'))
                ->with('success', 'FGM data has been saved successfully.');
        } catch (\Throwable $exception) {
            DB::rollBack();

            Log::error('FGM data save failed', [
                'user_id' => optional(Auth::user())->id,
                'error' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
            ]);

            return redirect(url('/dataentry/fgm'))
                ->withInput()
                ->with('error', 'FGM data could not be saved. Please review the form and try again.');
        }
    }
}
