<?php

namespace App\Modules\HR\Core\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Core\Models\RelationshipType;
use App\Modules\PLATFORM\Settings\Models\Branch;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class RelationshipTypeController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = RelationshipType::with('branch');

            return DataTables::of($query)
                ->addIndexColumn()
                ->addColumn('branch', fn ($row) => $row->branch?->name ?? '-')
                ->editColumn('status', function ($row) {
                    return $row->status
                        ? '<span class="badge bg-success">Active</span>'
                        : '<span class="badge bg-danger">Inactive</span>';
                })
                ->addColumn('action', function ($row) {
                    return view('core::relationship_types/partials/actions', compact('row'))->render();
                })
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('core::relationship_types/index');
    }

    public function create()
    {
        return view('core::relationship_types/create', [
            'branches' => Branch::where('status', true)->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name'      => 'required|string|max:100',
            'branch_id' => 'nullable|exists:branches,id',
        ], [
            'name.required' => 'Relationship type name is required.',
            'name.max' => 'Relationship type name must not exceed 100 characters.',
            'branch_id.exists' => 'The selected branch is invalid.',
        ]);

        RelationshipType::create([
            'branch_id' => $request->branch_id,
            'name'      => $request->name,
            'status'    => $request->has('status'),
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Relationship type created successfully',
        ]);
    }

    public function edit(RelationshipType $relationship_type)
    {
        return view('core::relationship_types/edit', [
            'relationshipType' => $relationship_type,
            'branches'         => Branch::where('status', true)->orderBy('name')->get(),
        ]);
    }

    public function update(Request $request, RelationshipType $relationship_type)
    {
        $request->validate([
            'name'      => 'required|string|max:100',
            'branch_id' => 'nullable|exists:branches,id',
        ], [
            'name.required' => 'Relationship type name is required.',
            'name.max' => 'Relationship type name must not exceed 100 characters.',
            'branch_id.exists' => 'The selected branch is invalid.',
        ]);

        $relationship_type->update([
            'branch_id' => $request->branch_id,
            'name'      => $request->name,
            'status'    => $request->has('status'),
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Relationship type updated successfully',
        ]);
    }

    public function destroy(RelationshipType $relationship_type)
    {
        // Check if relationship type is being used by employee families
        $employeeFamilyCount = DB::table('employee_families')
            ->where('relationship_type_id', $relationship_type->id)
            ->count();

        if ($employeeFamilyCount > 0) {
            return response()->json([
                'status' => false,
                'message' => 'Cannot delete this relationship type. It is currently being used by ' . $employeeFamilyCount . ' employee family record(s).',
            ], 422);
        }

        $relationship_type->delete();

        return response()->json([
            'status'  => true,
            'message' => 'Relationship type deleted successfully',
        ]);
    }

    public function status(RelationshipType $relationship_type)
    {
        $relationship_type->update([
            'status' => ! $relationship_type->status,
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Status updated successfully',
        ]);
    }
}
