<?php

namespace App\Http\Controllers;

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

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

    /**
     * Get a specific FreeLServLink record by FLSr_ID.
     */
    public function show($id)
    {
        $link = FreeLServLink::with(['serviceCategory', 'freelancerRegister'])->find($id);

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

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

    /**
     * Create a new FreeLServLink record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Srv_Id' => 'required|integer|exists:service_categories,srv_id',
            'FL_Id' => 'required|integer|exists:freelancer_register,FL_Id',
            'ListPriority' => 'nullable|string|in:1,2,3|max:1',
        ]);

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

        DB::beginTransaction(); // Start transaction

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

            // Create FreeLServLink record
            $link = FreeLServLink::create($validated);

            DB::commit(); // Commit transaction

            // Eager load the related data
            $link->load('serviceCategory', 'freelancerRegister');

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

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

    /**
     * Update a FreeLServLink record by FLSr_ID.
     */
    public function update(Request $request, $id)
    {
        $link = FreeLServLink::find($id);

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

        $validator = Validator::make($request->all(), [
            'Srv_Id' => 'nullable|integer|exists:service_categories,srv_id',
            'FL_Id' => 'nullable|integer|exists:freelancer_register,FL_Id',
            'ListPriority' => 'nullable|string|in:1,2,3|max:1',
        ]);

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

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

        $link->update($validated);

        $link->load('serviceCategory', 'freelancerRegister');

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

    /**
     * Delete a FreeLServLink record by FLSr_ID.
     */
    public function destroy($id)
    {
        $link = FreeLServLink::find($id);

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

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