<?php

namespace App\Http\Controllers\Api\Bank;

use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\Contractor;
use App\Models\FinancingApplication;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class BankController extends Controller
{
    /**
     * Get pending contractors for verification
     */
    public function pendingContractors(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            $contractors = Contractor::with(['user', 'legal', 'bankAccounts'])
                ->where('oap_status', 'pending')
                ->where('is_active', true)
                ->orderBy('created_at', 'asc')
                ->paginate(15);

            return response()->json([
                'success' => true,
                'data' => $contractors,
            ]);
        } catch (\Exception $e) {
            Log::error('Error get pending contractors: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data kontraktor: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Verify contractor
     */
    public function verifyContractor(Request $request, Contractor $contractor): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            $request->validate([
                'oap_status' => 'required|in:verified,rejected',
                'notes' => 'nullable|string',
            ]);

            $contractor->update([
                'oap_status' => $request->oap_status,
                'oap_verified_at' => now(),
                'oap_verified_by' => $user->id,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Status kontraktor berhasil diperbarui',
                'data' => $contractor->fresh(['user', 'legal']),
            ]);
        } catch (\Exception $e) {
            Log::error('Error verify contractor: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal verifikasi kontraktor: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get financing contracts
     */
    public function contracts(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            $status = $request->input('status');
            $query = Contract::with(['contractor', 'jobPackage'])
                ->whereIn('status', ['signed', 'execution']);

            if ($status) {
                $query->where('status', $status);
            }

            $contracts = $query->orderBy('created_at', 'desc')
                ->paginate(15);

            return response()->json([
                'success' => true,
                'data' => $contracts,
            ]);
        } catch (\Exception $e) {
            Log::error('Error get financing contracts: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data kontrak: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get financing detail
     */
    public function financingDetail(Contract $contract): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            $financing = FinancingApplication::where('contract_id', $contract->id)
                ->with(['bank', 'approvedBy'])
                ->first();

            return response()->json([
                'success' => true,
                'data' => [
                    'contract' => $contract->load(['contractor', 'jobPackage']),
                    'financing' => $financing,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error get financing detail: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil detail pembiayaan: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Approve financing
     */
    public function approveFinancing(Request $request, Contract $contract): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            $request->validate([
                'amount' => 'required|numeric|min:0',
                'interest_rate' => 'required|numeric|min:0|max:100',
                'tenor' => 'required|integer|min:1|max:60',
                'purpose' => 'nullable|string',
            ]);

            // Generate application number
            $year = date('Y');
            $count = FinancingApplication::whereYear('created_at', $year)->count() + 1;
            $appNumber = 'FIN/' . $year . '/' . str_pad($count, 4, '0', STR_PAD_LEFT);

            // Create financing application
            $financing = FinancingApplication::create([
                'contract_id' => $contract->id,
                'contractor_id' => $contract->contractor_id,
                'bank_id' => $user->id,
                'application_number' => $appNumber,
                'amount' => $request->amount,
                'interest_rate' => $request->interest_rate,
                'tenor' => $request->tenor,
                'purpose' => $request->purpose,
                'status' => 'submitted',
                'submitted_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Pengajuan pembiayaan berhasil dibuat',
                'data' => $financing,
            ]);
        } catch (\Exception $e) {
            Log::error('Error approve financing: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengajukan pembiayaan: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Disburse financing
     */
    public function disburse(Request $request, FinancingApplication $financing): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            if ($financing->status !== 'approved') {
                return response()->json([
                    'success' => false,
                    'message' => 'Pengajuan harus disetujui terlebih dahulu',
                ], 422);
            }

            $financing->update([
                'status' => 'disbursed',
                'disbursed_at' => now(),
                'approved_by' => $user->id,
                'approved_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Dana pembiayaan berhasil dicairkan',
                'data' => $financing,
            ]);
        } catch (\Exception $e) {
            Log::error('Error disburse financing: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mencairkan dana: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get bank statistics
     */
    public function statistics(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'bank') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: bank',
                ], 403);
            }

            $totalFinancing = FinancingApplication::count();
            $totalApproved = FinancingApplication::where('status', 'approved')->count();
            $totalDisbursed = FinancingApplication::where('status', 'disbursed')->count();
            $totalRejected = FinancingApplication::where('status', 'rejected')->count();
            
            $totalAmount = FinancingApplication::sum('amount');

            return response()->json([
                'success' => true,
                'data' => [
                    'total_applications' => $totalFinancing,
                    'approved' => $totalApproved,
                    'disbursed' => $totalDisbursed,
                    'rejected' => $totalRejected,
                    'total_amount' => (float) $totalAmount,
                    'total_amount_formatted' => 'Rp ' . number_format($totalAmount, 0, ',', '.'),
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error get bank statistics: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil statistik: ' . $e->getMessage(),
            ], 500);
        }
    }
}