<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AccountLawyerMapping;
use App\Models\AccountLawyerMappingLawyer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AccountLawyerMappingController extends Controller
{
    private function getPermissions(): array
    {
        $authUser = Auth::user();
        $perms = ['view' => true, 'add' => true, 'edit' => true, 'delete' => true];

        if (! $authUser->is_super_admin) {
            $userPermSlugs = $authUser->modulePermissions()
                ->wherePivot('is_active', true)
                ->pluck('slug')
                ->toArray();

            foreach (array_keys($perms) as $action) {
                $perms[$action] = in_array('accountlayer_' . $action, $userPermSlugs);
            }
        }

        return $perms;
    }

    /**
     * List all mappings.
     */
    public function index()
    {
        $perms = $this->getPermissions();

        $mappings = AccountLawyerMapping::with(['lawyers', 'creator'])
            ->orderByDesc('created_at')
            ->get()
            ->map(function ($m) {
                return [
                    'id'            => $m->id,
                    'accountNo'     => $m->loan_id,
                    'accountName'   => $m->customer_name ?? '',
                    'lawyerCount'   => $m->lawyers->count(),
                    'lawyers'       => $m->lawyers->map(fn ($l) => [
                        'id'   => $l->law_firm_id,
                        'name' => $l->law_firm_name ?? '',
                    ])->values(),
                    'assignDate'    => $m->assign_date?->format('d-M-Y') ?? '',
                    'csDate'        => $m->case_submitted_date?->format('d-M-Y') ?? '',
                    'caseReg'       => $m->case_registration_via ?? '',
                    'courtFee'      => number_format((float) $m->court_fee, 3),
                    'createdOn'     => $m->created_at?->format('d-M-Y') ?? '',
                    'createdBy'     => $m->creator->name ?? '',
                    'updatedOn'     => $m->updated_at?->format('d-M-Y') ?? '',
                    'status'        => $m->is_active ? 'Active' : 'Inactive',
                ];
            });

        return view('admin.account-lawyer.index', compact('mappings', 'perms'));
    }

    /**
     * Step 1: Search Account page.
     */
    public function searchAccount()
    {
        return view('admin.account-lawyer.search_account');
    }

    /**
     * Step 2: Search Lawyer page.
     */
    public function searchLawyer(Request $request)
    {
        $accountNo    = $request->query('accountNo', '');
        $customerName = $request->query('customerName', '');
        $principal    = $request->query('principal', '');
        $odi          = $request->query('odi', '');
        $crc          = $request->query('crc', '');
        $stmtDate     = $request->query('stmtDate', '');
        $stmtAmount   = $request->query('stmtAmount', '');

        return view('admin.account-lawyer.search_lawyer', compact(
            'accountNo', 'customerName', 'principal', 'odi', 'crc', 'stmtDate', 'stmtAmount'
        ));
    }

    /**
     * Step 3: Create Mapping form.
     */
    public function create(Request $request)
    {
        $accountNo    = $request->query('accountNo', '');
        $customerName = $request->query('customerName', '');
        $principal    = $request->query('principal', '');
        $odi          = $request->query('odi', '');
        $crc          = $request->query('crc', '');
        $stmtDate     = $request->query('stmtDate', '');
        $stmtAmount   = $request->query('stmtAmount', '');
        $lawyers      = $request->query('lawyers', ''); // JSON string of selected lawyers

        return view('admin.account-lawyer.create', compact(
            'accountNo', 'customerName', 'principal', 'odi', 'crc', 'stmtDate', 'stmtAmount', 'lawyers'
        ));
    }

    /**
     * Store mapping to DB.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'loan_id'               => 'required|string|max:50',
            'customer_name'         => 'nullable|string|max:255',
            'principal_os_amount'   => 'nullable|numeric',
            'odi_amount'            => 'nullable|numeric',
            'crc_amount'            => 'nullable|numeric',
            'statement_date'        => 'nullable|date',
            'statement_amount'      => 'nullable|numeric',
            'assign_date'           => 'required|date',
            'case_submitted_date'   => 'required|date',
            'case_registration_via' => 'required|string|max:255',
            'court_fee'             => 'required|numeric|min:0',
            'case_filed_date'       => 'required|date',
            'internal_remarks'      => 'nullable|string|max:2000',
            'lawyers'               => 'required|json',
        ]);

        $lawyersData = json_decode($validated['lawyers'], true);

        if (empty($lawyersData)) {
            return response()->json(['success' => false, 'message' => 'At least one lawyer is required.'], 422);
        }

        DB::beginTransaction();
        try {
            $mapping = AccountLawyerMapping::create([
                'loan_id'               => $validated['loan_id'],
                'customer_name'         => $validated['customer_name'] ?? null,
                'principal_os_amount'   => $validated['principal_os_amount'] ?? null,
                'odi_amount'            => $validated['odi_amount'] ?? null,
                'crc_amount'            => $validated['crc_amount'] ?? null,
                'statement_date'        => $validated['statement_date'] ?? null,
                'statement_amount'      => $validated['statement_amount'] ?? null,
                'assign_date'           => $validated['assign_date'],
                'case_submitted_date'   => $validated['case_submitted_date'],
                'case_registration_via' => $validated['case_registration_via'],
                'court_fee'             => $validated['court_fee'],
                'case_filed_date'       => $validated['case_filed_date'],
                'internal_remarks'      => $validated['internal_remarks'] ?? null,
                'created_by'            => Auth::id(),
            ]);

            foreach ($lawyersData as $lawyer) {
                AccountLawyerMappingLawyer::create([
                    'mapping_id'    => $mapping->id,
                    'law_firm_id'   => $lawyer['id'] ?? '',
                    'law_firm_name' => $lawyer['name'] ?? '',
                    'address'       => $lawyer['address'] ?? '',
                    'email'         => $lawyer['email'] ?? '',
                    'mobile'        => $lawyer['mobile'] ?? '',
                    'user_id'       => $lawyer['user_id'] ?? null,
                ]);
            }

            DB::commit();

            return response()->json(['success' => true, 'mapping_id' => $mapping->id]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Edit mapping — returns JSON for AJAX popup.
     */
    public function edit(AccountLawyerMapping $mapping)
    {
        $mapping->load('lawyers');

        return response()->json([
            'success' => true,
            'mapping' => [
                'id'                    => $mapping->id,
                'loan_id'               => $mapping->loan_id,
                'customer_name'         => $mapping->customer_name,
                'assign_date'           => $mapping->assign_date?->format('Y-m-d'),
                'case_submitted_date'   => $mapping->case_submitted_date?->format('Y-m-d'),
                'case_registration_via' => $mapping->case_registration_via,
                'court_fee'             => $mapping->court_fee,
                'case_filed_date'       => $mapping->case_filed_date?->format('Y-m-d'),
                'internal_remarks'      => $mapping->internal_remarks,
                'lawyers'               => $mapping->lawyers->map(fn ($l) => [
                    'id'      => $l->law_firm_id,
                    'name'    => $l->law_firm_name,
                    'address' => $l->address,
                    'email'   => $l->email,
                    'mobile'  => $l->mobile,
                    'user_id' => $l->user_id,
                ]),
            ],
        ]);
    }

    /**
     * Update mapping.
     */
    public function update(Request $request, AccountLawyerMapping $mapping)
    {
        $validated = $request->validate([
            'assign_date'           => 'required|date',
            'case_submitted_date'   => 'required|date',
            'case_registration_via' => 'required|string|max:255',
            'court_fee'             => 'required|numeric|min:0',
            'case_filed_date'       => 'required|date',
            'internal_remarks'      => 'nullable|string|max:2000',
            'lawyers'               => 'required|json',
        ]);

        $lawyersData = json_decode($validated['lawyers'], true);

        if (empty($lawyersData)) {
            return response()->json(['success' => false, 'message' => 'At least one lawyer is required.'], 422);
        }

        DB::beginTransaction();
        try {
            $mapping->update([
                'assign_date'           => $validated['assign_date'],
                'case_submitted_date'   => $validated['case_submitted_date'],
                'case_registration_via' => $validated['case_registration_via'],
                'court_fee'             => $validated['court_fee'],
                'case_filed_date'       => $validated['case_filed_date'],
                'internal_remarks'      => $validated['internal_remarks'] ?? null,
                'updated_by'            => Auth::id(),
            ]);

            // Replace all lawyers
            $mapping->lawyers()->delete();
            foreach ($lawyersData as $lawyer) {
                AccountLawyerMappingLawyer::create([
                    'mapping_id'    => $mapping->id,
                    'law_firm_id'   => $lawyer['id'] ?? '',
                    'law_firm_name' => $lawyer['name'] ?? '',
                    'address'       => $lawyer['address'] ?? '',
                    'email'         => $lawyer['email'] ?? '',
                    'mobile'        => $lawyer['mobile'] ?? '',
                    'user_id'       => $lawyer['user_id'] ?? null,
                ]);
            }

            DB::commit();
            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Delete mapping.
     */
    public function destroy(AccountLawyerMapping $mapping)
    {
        $mapping->delete();
        return response()->json(['success' => true]);
    }

    /**
     * Success page.
     */
    public function success(Request $request)
    {
        $accountNo = $request->query('accountNo', '');
        return view('admin.account-lawyer.success', compact('accountNo'));
    }
}
