<?php

namespace App\Http\Controllers;

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

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

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

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

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

    /**
     * Create a new FreeLClasssified 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',
            'Flp_Title' => 'nullable|string|max:25',
        ]);

        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 FreeLClasssified record
            $classified = FreeLClasssified::create($validated);

            DB::commit(); // Commit transaction

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

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

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

    /**
     * Update a FreeLClasssified record by FLC_Id.
     */
    public function update(Request $request, $id)
    {
        $classified = FreeLClasssified::find($id);

        if (!$classified) {
            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',
            'Flp_Title' => 'nullable|string|max:25',
        ]);

        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');
        }

        $classified->update($validated);

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

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

    /**
     * Delete a FreeLClasssified record by FLC_Id.
     */
    public function destroy($id)
    {
        $classified = FreeLClasssified::find($id);

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

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