<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Bank;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class BankController extends Controller
{
    // public function index()
    // {
    //     return response()->json(['data' => Bank::withCount('bankAccounts')->orderBy('bank_name')->get()]);
    // }

public function index(Request $request)
{
    try {
        $perPage = $request->get('per_page', 10);
        $search  = $request->get('search');

        $banks = Bank::withCount('bankAccounts')
            ->when($request->bank_code, fn ($q, $v) => $q->where('bank_code', $v))
            ->when($request->bank_name, fn ($q, $v) => $q->where('bank_name', 'LIKE', "%{$v}%"))
            ->when($request->short_name, fn ($q, $v) => $q->where('short_name', 'LIKE', "%{$v}%"))
            ->when($request->filled('is_active'), fn ($q) => $q->where('is_active', $request->is_active))

            ->when($search, function ($query) use ($search) {
                $query->where(function ($q) use ($search) {
                    $q->where('bank_name', 'LIKE', "%{$search}%")
                      ->orWhere('bank_code', 'LIKE', "%{$search}%")
                      ->orWhere('short_name', 'LIKE', "%{$search}%");
                });
            })

            ->orderBy('bank_name', 'ASC')
            ->paginate($perPage);

        return response()->json([
            'success' => true,
            'message' => 'Bank list fetched successfully.',
            'data'    => $banks
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch bank list.',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}



    public function show($id)
{
    try {
        $bank = Bank::with('bankAccounts')
            ->findOrFail($id);

        return response()->json([
            'success' => true,
            'message' => 'Bank details fetched successfully.',
            'data'    => $bank
        ], 200);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Bank not found.',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 404);
    }
}


public function GetAll(Request $request)
{
    try {
        $search = $request->search;

        $query = Bank::withCount('bankAccounts')

            ->when($request->bank_code, fn ($q, $v) => $q->where('bank_code', $v))
            ->when($request->bank_name, fn ($q, $v) => $q->where('bank_name', 'LIKE', "%{$v}%"))
            ->when($request->short_name, fn ($q, $v) => $q->where('short_name', 'LIKE', "%{$v}%"))
            ->when($request->filled('is_active'), fn ($q) => $q->where('is_active', $request->is_active))

            ->when($search, function ($query) use ($search) {
                $query->where(function ($q) use ($search) {
                    $q->where('bank_name', 'LIKE', "%{$search}%")
                      ->orWhere('bank_code', 'LIKE', "%{$search}%")
                      ->orWhere('short_name', 'LIKE', "%{$search}%");
                });
            })

            ->orderBy('bank_name', 'ASC');

        $data = $request->filled('per_page')
            ? $query->paginate($request->per_page)
            : $query->get();

        return response()->json([
            'success' => true,
            'message' => 'Bank list fetched successfully.',
            'data'    => $data
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch bank list.',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

    public function store(Request $request)
    {
        $data = $request->validate([
            'bank_code'   => 'required|string|unique:banks,bank_code',
            'bank_name'   => 'required|string|max:200',
            'short_name'  => 'nullable|string|max:50',
            'ifsc_prefix' => 'nullable|string|max:10',
            'is_active'   => 'boolean',
        ]);
        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('bank_logos', 'public');
        }
        $bank = Bank::create($data);
       
        return response()->json($bank, 201);
    }

    public function update(Request $request, $id)
    {
        $bank = Bank::findOrFail($id);
        $data = $request->validate([
            'bank_code' => [
            'required',
            'string',
            Rule::unique('banks', 'bank_code')->ignore($bank->Bank_Id, 'Bank_Id'),
        ],
            'bank_name'   => 'required|string|max:200',
            'short_name'  => 'nullable|string|max:50',
            'ifsc_prefix' => 'nullable|string|max:10',
            'is_active'   => 'boolean',
        ]);
        if ($request->hasFile('logo')) {
            if ($bank->logo) Storage::disk('public')->delete($bank->logo);
            $data['logo'] = $request->file('logo')->store('bank_logos', 'public');
        }
        $bank->update($data);
        
        return response()->json($bank);
    }

    public function destroy($id)
    {
        $bank = Bank::findOrFail($id);
        if ($bank->bankAccounts()->exists()) {
            return response()->json(['message' => 'Cannot delete: bank has linked accounts.'], 422);
        }
        $bank->delete();
       
        return response()->json(['message' => 'Deleted.']);
    }
}
