<?php

namespace App\Http\Controllers;

use App\Models\PaymentAccount;
use Illuminate\Http\Request;

class PaymentAccountController extends Controller
{
    public function index(Request $request)
    {
        $query = PaymentAccount::query();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('provider', 'like', "%{$search}%")
                  ->orWhere('account_number', 'like', "%{$search}%")
                  ->orWhere('account_holder', 'like', "%{$search}%");
            });
        }

        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        if ($request->filled('status')) {
            $query->where('is_active', $request->status === 'active');
        }

        $accounts = $query->latest()->paginate(15)->withQueryString();

        return view('pages.payment-accounts.index', [
            'title' => 'Rekening Pembayaran',
            'accounts' => $accounts,
        ]);
    }

    public function create()
    {
        return view('pages.payment-accounts.form', [
            'title' => 'Tambah Rekening',
            'account' => new PaymentAccount(),
            'bankProviders' => PaymentAccount::getBankProviders(),
            'ewalletProviders' => PaymentAccount::getEwalletProviders(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'type' => 'required|in:bank,ewallet',
            'provider' => 'required|string|max:50',
            'account_number' => 'required|string|max:50',
            'account_holder' => 'required|string|max:100',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        PaymentAccount::create($validated);

        return redirect()->route('payment-accounts.index')
            ->with('success', 'Rekening pembayaran berhasil ditambahkan.');
    }

    public function edit(PaymentAccount $paymentAccount)
    {
        return view('pages.payment-accounts.form', [
            'title' => 'Edit Rekening',
            'account' => $paymentAccount,
            'bankProviders' => PaymentAccount::getBankProviders(),
            'ewalletProviders' => PaymentAccount::getEwalletProviders(),
        ]);
    }

    public function update(Request $request, PaymentAccount $paymentAccount)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'type' => 'required|in:bank,ewallet',
            'provider' => 'required|string|max:50',
            'account_number' => 'required|string|max:50',
            'account_holder' => 'required|string|max:100',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $paymentAccount->update($validated);

        return redirect()->route('payment-accounts.index')
            ->with('success', 'Rekening pembayaran berhasil diperbarui.');
    }

    public function destroy(PaymentAccount $paymentAccount)
    {
        // Check if account has payments
        if ($paymentAccount->payments()->exists()) {
            return redirect()->back()
                ->with('error', 'Rekening tidak dapat dihapus karena sudah digunakan pada pembayaran.');
        }

        $paymentAccount->delete();

        return redirect()->route('payment-accounts.index')
            ->with('success', 'Rekening pembayaran berhasil dihapus.');
    }

    public function toggleStatus(PaymentAccount $paymentAccount)
    {
        $paymentAccount->update([
            'is_active' => !$paymentAccount->is_active,
        ]);

        $status = $paymentAccount->is_active ? 'diaktifkan' : 'dinonaktifkan';

        return redirect()->back()
            ->with('success', "Rekening {$paymentAccount->name} berhasil {$status}.");
    }
}
