<?php

namespace App\Http\Controllers;

use App\Models\FreeLServOffer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class FreeLServOfferController extends Controller
{
    /**
     * Get all FreeLServOffer records.
     */
    public function index()
    {
        $offers = FreeLServOffer::with(['freeLPackMast', 'freelancerRegister'])->get();
        return response()->json($offers);
    }

    /**
     * Get a specific FreeLServOffer record by FLPL_Id.
     */
    public function show($id)
    {
        $offer = FreeLServOffer::with(['freeLPackMast', 'freelancerRegister'])->find($id);

        if (!$offer) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        return response()->json($offer);
    }

    /**
     * Create a new FreeLServOffer record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'FLP_Id' => 'nullable|integer|exists:free_l_pack_mast,FLP_Id',
            'FL_Id' => 'nullable|integer|exists:freelancer_register,FL_Id',
            'STDate' => 'nullable|date_format:d/m/Y',
            'EdDate' => 'nullable|date_format:d/m/Y',
            'Status' => 'nullable|string|in:A,I|max:1',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        DB::beginTransaction(); // Start transaction

        try {
            $validated = $validator->validated();

            // Convert date fields to MySQL format
            $validated['STDate'] = $request->filled('STDate')
                ? Carbon::createFromFormat('d/m/Y', $request->input('STDate'), 'Asia/Kolkata')
                    ->startOfDay()
                    ->format('Y-m-d H:i:s')
                : null;
            $validated['EdDate'] = $request->filled('EdDate')
                ? Carbon::createFromFormat('d/m/Y', $request->input('EdDate'), 'Asia/Kolkata')
                    ->startOfDay()
                    ->format('Y-m-d H:i:s')
                : null;

            // Create FreeLServOffer record
            $offer = FreeLServOffer::create($validated);

            DB::commit(); // Commit transaction

            // Eager load the related data
            $offer->load('freeLPackMast', 'freelancerRegister');

            return response()->json([
                'message' => 'Freelancer service offer registered successfully!',
                'offer' => $offer
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack(); // Rollback on failure
            return response()->json(['error' => 'Freelancer service offer registration failed!', 'details' => $e->getMessage()], 500);
        }
    }

    /**
     * Update a FreeLServOffer record by FLPL_Id.
     */
    public function update(Request $request, $id)
    {
        $offer = FreeLServOffer::find($id);

        if (!$offer) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'FLP_Id' => 'nullable|integer|exists:free_l_pack_mast,FLP_Id',
            'FL_Id' => 'nullable|integer|exists:freelancer_register,FL_Id',
            'STDate' => 'nullable|date_format:d/m/Y',
            'EdDate' => 'nullable|date_format:d/m/Y',
            'Status' => 'nullable|string|in:A,I|max:1',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $validated = array_filter($validator->validated());

        // Convert date fields to MySQL format
        if ($request->filled('STDate')) {
            $validated['STDate'] = Carbon::createFromFormat('d/m/Y', $request->input('STDate'), 'Asia/Kolkata')
                ->startOfDay()
                ->format('Y-m-d H:i:s');
        }
        if ($request->filled('EdDate')) {
            $validated['EdDate'] = Carbon::createFromFormat('d/m/Y', $request->input('EdDate'), 'Asia/Kolkata')
                ->startOfDay()
                ->format('Y-m-d H:i:s');
        }

        $offer->update($validated);

        $offer->load('freeLPackMast', 'freelancerRegister');

        return response()->json($offer);
    }

    /**
     * Delete a FreeLServOffer record by FLPL_Id.
     */
    public function destroy($id)
    {
        $offer = FreeLServOffer::find($id);

        if (!$offer) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $offer->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
