<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\CompanyController;
use App\Http\Controllers\Api\DepartmentController;
use App\Http\Controllers\Api\EmployeeController;
use App\Http\Controllers\Api\DashboardController;
use App\Http\Controllers\Api\CompanyDashboardController;
use App\Http\Controllers\Api\RoleController;
use App\Http\Controllers\Api\PermissionController;
use App\Http\Controllers\Api\LoanController;
use App\Http\Controllers\Api\ProfitSweepController;
use App\Http\Controllers\Api\GroupDashboardController;
use App\Http\Controllers\Api\AuditLogController;
use App\Http\Controllers\Api\EmployeeRecordController;
use App\Http\Controllers\Api\InvestorController;
use App\Http\Controllers\Api\TreasuryController;
use App\Http\Controllers\Api\InvoiceController;
use App\Http\Controllers\Api\AiController;
use App\Http\Controllers\Api\StaffLoanController;
use App\Http\Controllers\Api\SuperAdminBankAccountController;
use App\Http\Controllers\Api\SuperAdminDashboardController;

Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/me', [AuthController::class, 'me']);
    Route::put('/profile', [AuthController::class, 'updateProfile']);
    Route::post('/change-password', [AuthController::class, 'changePassword']);

    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/analytics', [DashboardController::class, 'analytics']);
    Route::get('/dashboard/company', [CompanyDashboardController::class, 'index']);

    // Specific company routes MUST come before the resource to avoid wildcard capture
    Route::get('/companies/lenders-list', function(\Illuminate\Http\Request $req) {
        $user = $req->user();
        $exclude = $user->company_id ?? 0;
        $companies = \App\Models\Company::where('id', '!=', $exclude)
            ->select('id', 'name', 'is_holding_company')
            ->orderByDesc('is_holding_company')
            ->orderBy('name')
            ->get();
        return response()->json(['data' => $companies]);
    });
    Route::apiResource('companies', CompanyController::class);
    Route::get('/companies/{id}/statistics', [CompanyController::class, 'statistics']);

    // Bank Accounts
    Route::get('/bank-accounts/list', [App\Http\Controllers\Api\BankAccountController::class, 'list'])->middleware('company.scope');
    Route::apiResource('bank-accounts', App\Http\Controllers\Api\BankAccountController::class)->middleware('company.scope');
    Route::post('/bank-accounts/transfer', [App\Http\Controllers\Api\BankAccountController::class, 'transfer'])->middleware('company.scope');

    // Super Admin Bank Accounts - Public list for company users to select holding accounts
    Route::get('/super-admin-bank-accounts/public-list', [SuperAdminBankAccountController::class, 'publicList']);

    // Super Admin Bank Accounts - Admin only
    Route::middleware('role:Super Admin')->group(function () {
        Route::get('/super-admin-bank-accounts/list', [SuperAdminBankAccountController::class, 'list']);
        Route::apiResource('super-admin-bank-accounts', SuperAdminBankAccountController::class);
    });

    Route::apiResource('departments', DepartmentController::class)->middleware('company.scope');

    Route::apiResource('employees', EmployeeController::class)->middleware('company.scope');
    Route::post('/employees/bulk-import', [EmployeeController::class, 'bulkImport'])->middleware('company.scope');

    // Role & Permission Management
    Route::apiResource('roles', RoleController::class);
    Route::post('/roles/assign', [RoleController::class, 'assignRole']);
    Route::post('/roles/revoke', [RoleController::class, 'revokeRole']);
    Route::get('/permissions', [PermissionController::class, 'index']);

    // User Management (company-scoped)
    Route::apiResource('users', App\Http\Controllers\Api\UserController::class)->middleware('company.scope');

    // Audit Logs
    Route::get('/audit-logs', [AuditLogController::class, 'index'])->middleware('company.scope');
    Route::get('/audit-logs/stats', [AuditLogController::class, 'stats'])->middleware('company.scope');
    Route::get('/audit-logs/company/{companyId}', [AuditLogController::class, 'companyAudit'])->middleware('company.scope');
    Route::get('/audit-logs/employee/{employeeId}', [AuditLogController::class, 'employeeAudit'])->middleware('company.scope');

    // Inter-Company Loan System
    Route::get('/loans', [LoanController::class, 'index'])->middleware('company.scope');
    Route::post('/loans', [LoanController::class, 'store'])->middleware('company.scope');
    Route::post('/loans/{id}/approve', [LoanController::class, 'approve'])->middleware('company.scope');
    Route::post('/loans/{id}/reject', [LoanController::class, 'reject'])->middleware('company.scope');
    Route::get('/loans/{id}/repayments', [LoanController::class, 'repayments'])->middleware('company.scope');
    Route::post('/loans/{id}/repay', [LoanController::class, 'repay'])->middleware('company.scope');
    Route::post('/loan-repayments/{repaymentId}/confirm', [LoanController::class, 'confirmRepayment'])->middleware('company.scope');
    Route::post('/loan-repayments/{repaymentId}/reject', [LoanController::class, 'rejectRepayment'])->middleware('company.scope');

    // Profit Sweeps
    Route::get('/profit-sweeps', [ProfitSweepController::class, 'sweeps'])->middleware('company.scope');
    Route::get('/profit-sweeps/available-months', [ProfitSweepController::class, 'availableMonths'])->middleware('company.scope');
    Route::get('/profit-sweep-rules', [ProfitSweepController::class, 'rules'])->middleware('company.scope');
    Route::post('/profit-sweep-rules', [ProfitSweepController::class, 'storeRule']);
    Route::post('/profit-sweeps/execute', [ProfitSweepController::class, 'store'])->middleware('company.scope');
    Route::post('/profit-sweeps/{id}/receipt', [ProfitSweepController::class, 'uploadReceipt'])->middleware('company.scope');

    // Company Assets
    Route::apiResource('company-assets', App\Http\Controllers\Api\CompanyAssetController::class)->middleware('company.scope');

    // Employee Logs
    Route::apiResource('employee-logs', App\Http\Controllers\Api\EmployeeLogController::class)->middleware('company.scope');

    // Employee Records (leave, salary history, events/awards/fines)
    Route::get('/employees/{id}/leaves', [EmployeeRecordController::class, 'getLeaves']);
    Route::post('/employees/{id}/leaves', [EmployeeRecordController::class, 'addLeave']);
    Route::get('/employees/{id}/salary-history', [EmployeeRecordController::class, 'getSalaryHistory']);
    Route::post('/employees/{id}/salary-change', [EmployeeRecordController::class, 'addSalaryChange']);
    Route::get('/employees/{id}/events', [EmployeeRecordController::class, 'getEvents']);
    Route::post('/employees/{id}/events', [EmployeeRecordController::class, 'addEvent']);

    // Company Financials update
    Route::put('/company/financials', [EmployeeRecordController::class, 'updateCompanyFinancials']);
    Route::get('/company/financial-logs', [EmployeeRecordController::class, 'financialLogs']);

    // Monthly Financial Management (unified revenue/expense entry)
    Route::get('/monthly-financials', [App\Http\Controllers\Api\MonthlyFinancialController::class, 'index'])->middleware('company.scope');
    Route::post('/monthly-financials', [App\Http\Controllers\Api\MonthlyFinancialController::class, 'store'])->middleware('company.scope');
    Route::get('/monthly-financials/{yearMonth}/history', [App\Http\Controllers\Api\MonthlyFinancialController::class, 'history'])->middleware('company.scope');

    // Group God-View Dashboard
    Route::get('/dashboard/group', [GroupDashboardController::class, 'index']);

    // Super Admin Dashboard
    Route::middleware('role:Super Admin')->group(function () {
        Route::get('/dashboard/super-admin', [SuperAdminDashboardController::class, 'index']);
    });

    // Treasury (group-wide financial overview)
    Route::get('/treasury', [TreasuryController::class, 'index']);

    // Invoices
    Route::get('/invoices', [InvoiceController::class, 'index']);
    Route::get('/invoices/profit-allocation', [InvoiceController::class, 'profitAllocationInvoices']);
    Route::post('/invoices', [InvoiceController::class, 'store']);
    Route::get('/invoices/{id}', [InvoiceController::class, 'show']);
    Route::patch('/invoices/{id}/status', [InvoiceController::class, 'updateStatus']);
    Route::post('/invoices/{id}/mark-paid', [InvoiceController::class, 'markPaid']);

    // Expenses
    Route::get('/expenses', function (Request $request) {
        $companyId = $request->user()->company_id;
        $expenses = \App\Models\Expense::where('company_id', $companyId)
            ->with('category')
            ->latest()
            ->get()
            ->map(fn($e) => array_merge($e->toArray(), ['category' => $e->category?->name ?? 'General']));
        return response()->json(['data' => $expenses]);
    })->middleware('company.scope');

    // Investors & Partners
    Route::get('/investors', [InvestorController::class, 'index']);
    Route::post('/investors', [InvestorController::class, 'store']);
    Route::get('/investors/{id}', [InvestorController::class, 'show']);
    Route::post('/investors/{id}', [InvestorController::class, 'update']); // POST for multipart/form-data
    Route::delete('/investors/{id}', [InvestorController::class, 'destroy']);
    Route::get('/investors/{id}/payments', [InvestorController::class, 'payments']);
    Route::post('/investors/{id}/payments', [InvestorController::class, 'addPayment']);

    Route::post('/expenses', function (Request $request) {
        $validated = $request->validate([
            'title'               => 'required|string|max:255',
            'amount'              => 'required|numeric|min:0.01',
            'expense_category_id' => 'nullable|integer',
            'expense_date'        => 'required|date',
            'description'         => 'nullable|string|max:2000',
            'vendor_name'         => 'nullable|string|max:255',
            'bank_account_id'     => 'nullable|integer|exists:bank_accounts,id',
            'receipt'             => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
        ]);
        $companyId = $request->user()->company_id;
        if (!$companyId) {
            return response()->json(['message' => 'Your account is not linked to a company. Please contact your administrator.'], 422);
        }
        // Validate bank account belongs to company
        if ($validated['bank_account_id']) {
            $bankAccount = \App\Models\BankAccount::where('id', $validated['bank_account_id'])
                ->where('company_id', $companyId)
                ->first();
            if (!$bankAccount) {
                return response()->json(['message' => 'Invalid bank account'], 422);
            }
        }
        // Resolve category: use provided ID, else first company category, else create default
        $catId = $validated['expense_category_id'] ?? null;
        if (!$catId) {
            $cat = \App\Models\ExpenseCategory::where('company_id', $companyId)->first();
            if (!$cat) {
                $cat = \App\Models\ExpenseCategory::create(['company_id' => $companyId, 'name' => 'General', 'is_active' => true]);
            }
            $catId = $cat->id;
        }
        // Look up employee record for this user; fallback to null if none exists
        $employee = \App\Models\Employee::where('user_id', $request->user()->id)->first();

        $data = [
            'company_id'          => $companyId,
            'bank_account_id'     => $validated['bank_account_id'] ?? null,
            'employee_id'         => $employee?->id,
            'title'               => $validated['title'],
            'amount'              => $validated['amount'],
            'expense_category_id' => $catId,
            'expense_date'        => $validated['expense_date'],
            'description'         => $validated['description'] ?? '',
            'vendor_name'         => $validated['vendor_name'] ?? '',
            'status'              => 'submitted',
        ];
        if ($request->hasFile('receipt')) {
            $data['receipt_file'] = $request->file('receipt')->store('expense_receipts', 'public');
        }
        $expense = \App\Models\Expense::create($data);

        // Debit bank account if specified and expense is approved/paid
        if ($expense->bankAccount && ($expense->status === 'approved' || $expense->status === 'paid')) {
            $expense->bankAccount->debit($expense->amount);
        } elseif (!$expense->bankAccount && ($expense->status === 'approved' || $expense->status === 'paid')) {
            // If no bank account and expense is approved/paid, deduct from cash balance
            $company = \App\Models\Company::find($companyId);
            if ($company) {
                $company->decrement('cash_balance', $expense->amount);
            }
        }

        return response()->json(['data' => $expense->load('category', 'bankAccount')], 201);
    })->middleware('company.scope');

    Route::patch('/expenses/{id}/status', function (Request $request, $id) {
        $user = $request->user();
        $expense = \App\Models\Expense::whereHas('company', function ($q) use ($user) {
            if (!$user->hasRole('Super Admin')) {
                $q->where('id', $user->company_id);
            }
        })->findOrFail($id);

        $validated = $request->validate([
            'status' => 'required|in:submitted,approved,rejected,paid',
            'rejection_reason' => 'nullable|string|max:500',
        ]);

        $oldStatus = $expense->status;
        $update = ['status' => $validated['status']];
        if ($validated['status'] === 'approved') {
            $update['approved_by'] = $user->id;
            $update['approved_at'] = now();
        }
        if ($validated['status'] === 'rejected' && isset($validated['rejection_reason'])) {
            $update['rejection_reason'] = $validated['rejection_reason'];
        }

        $expense->update($update);

        // Update bank balance when expense is approved or paid (transition from non-approved/paid state)
        if (($validated['status'] === 'approved' || $validated['status'] === 'paid') &&
            $oldStatus !== 'approved' && $oldStatus !== 'paid') {
            if ($expense->bankAccount) {
                $expense->bankAccount->debit($expense->amount);
            } else {
                // If no bank account, deduct from cash balance
                $company = \App\Models\Company::find($expense->company_id);
                if ($company) {
                    $company->decrement('cash_balance', $expense->amount);
                }
            }
        }

        return response()->json(['data' => $expense->load('category', 'bankAccount'), 'message' => 'Status updated to ' . $validated['status']]);
    })->middleware('company.scope');

    // ── Staff Loans ────────────────────────────────────────────
    Route::get('/staff-loans',                                  [StaffLoanController::class, 'index']);
    Route::post('/staff-loans',                                 [StaffLoanController::class, 'store']);
    Route::post('/staff-loans/{id}/approve',                    [StaffLoanController::class, 'approve']);
    Route::post('/staff-loans/{id}/reject',                     [StaffLoanController::class, 'reject']);
    Route::get('/staff-loans/{id}/deductions',                  [StaffLoanController::class, 'deductions']);
    Route::post('/staff-loan-deductions/{id}/mark-deducted',    [StaffLoanController::class, 'markDeducted']);

    // ── Sarkin Mota AI ──────────────────────────────────────────────
    Route::post('/ai/chat', [AiController::class, 'chat']);
});
