<?php

namespace App\Http\Controllers;

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

class FreelancerRegisterController extends Controller
{
    /**
     * Get all FreelancerRegister records.
     */
    public function index()
    {
        $freelancers = FreelancerRegister::with(['society', 'user', 'sociRes'])->get();
        return response()->json($freelancers);
    }

    /**
     * Get a specific FreelancerRegister record by FL_Id.
     */
    public function show($id)
    {
        $freelancer = FreelancerRegister::with(['society', 'user', 'sociRes'])->find($id);

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

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

    /**
     * Create a new FreelancerRegister record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SocId' => 'required|integer|exists:society_master,SocId',
            'U_Id' => 'required|integer|exists:users_master,U_Id',
            'SR_Id' => 'nullable|integer|exists:soci_reso_books,SR_Id',
            'BusinessName' => 'required|string|max:255',
            'Registration' => 'required|string|max:25',
            'TaxRegistration' => 'required|string|max:25',
            '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 FreelancerRegister record
            $freelancer = FreelancerRegister::create($validated);

            DB::commit(); // Commit transaction

            // Eager load the related data
            $freelancer->load('society', 'user', 'sociRes');

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

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

    /**
     * Update a FreelancerRegister record by FL_Id.
     */
    public function update(Request $request, $id)
    {
        $freelancer = FreelancerRegister::find($id);

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

        $validator = Validator::make($request->all(), [
            'SocId' => 'nullable|integer|exists:society_master,SocId',
            'U_Id' => 'nullable|integer|exists:users_master,U_Id',
            'SR_Id' => 'nullable|integer|exists:soci_reso_books,SR_Id',
            'BusinessName' => 'nullable|string|max:255',
            'Registration' => 'nullable|string|max:25',
            'TaxRegistration' => 'nullable|string|max:25',
            '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');
        }

        $freelancer->update($validated);

        $freelancer->load('society', 'user', 'sociRes');

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

    /**
     * Delete a FreelancerRegister record by FL_Id.
     */
    public function destroy($id)
    {
        $freelancer = FreelancerRegister::find($id);

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

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