<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\SystemSetting;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class TransactionController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();
        $query = Transaction::with('user')
            ->where([
                'user_id' => $user->id
            ]);

        // Filter by month and year if provided
        if ($request->filled('month') && $request->filled('year')) {
            $month = $request->input('month');
            $year = $request->input('year');

            $query->whereYear('created_at', $year)
                  ->whereMonth('created_at', $month); // dayjs month is 0-based, MySQL is 1-based
        }

        $transactions = $query->latest()
            ->paginate(5)
            ->withQueryString();

        return Inertia::render('transaction', [
            'transactions' => $transactions
        ]);
    }

    public function filter(Request $request)
    {
        try {
            $user = auth()->user();
            $query = Transaction::with('user')
                ->where([
                    'user_id' => $user->id
                ]);

            // Filter by month and year if provided
            if ($request->filled('month') && $request->filled('year')) {
                $month = (int) $request->input('month');
                $year = (int) $request->input('year');

                $query->whereYear('created_at', $year)
                        ->whereMonth('created_at', $month + 1); // dayjs month is 0-based, MySQL is 1-based
            }

            $transactions = $query->latest()->get();

            return response()->json([
                'transactions' => $transactions,
                'filters' => [
                    'month' => $request->input('month'),
                    'year' => $request->input('year'),
                ],
                'success' => true,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to fetch transactions',
                'message' => $e->getMessage(),
                'success' => false,
            ], 500);
        }
    }

    public function create()
    {
        $users = User::select('id', 'name', 'email')->get();

        return Inertia::render('admin/transactions/create', [
            'users' => $users,
            'types' => ['Tambah Baki', 'Pemindahan', 'Bayar Bil', 'Pengeluaran', 'Penambahan System', 'Pengurangan System'],
            'statuses' => ['pending', 'processing', 'completed', 'failed'],
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'evidence' => 'nullable|url|max:500',
        ]);

        Transaction::create($validated);

        return redirect()->route('admin.transactions.index')
            ->with('message', 'Transaction created successfully.');
    }

    public function show(Transaction $transaction)
    {
        $transaction->load('user');

        return Inertia::render('admin/transactions/show', [
            'transaction' => $transaction,
        ]);
    }

    public function edit(Transaction $transaction)
    {
        $users = User::select('id', 'name', 'email')->get();

        return Inertia::render('admin/transactions/edit', [
            'transaction' => $transaction,
            'users' => $users,
            'types' => ['Tambah Baki', 'Pemindahan', 'Bayar Bil', 'Pengeluaran', 'Penambahan System', 'Pengurangan System'],
            'statuses' => ['pending', 'processing', 'completed', 'failed'],
        ]);
    }

    public function update(Request $request, Transaction $transaction)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'type' => 'required|in:Tambah Baki,Pemindahan,Bayar Bil,Pengeluaran,Penambahan System,Pengurangan System',
            'amount' => 'required|numeric|min:0.01',
            'status' => 'required|in:pending,processing,completed,failed',
            'reference' => 'required|string|max:255|unique:transactions,reference,' . $transaction->id,
            'recipient' => 'required|string|max:255',
            'evidence' => 'nullable|url|max:500',
            'notes' => 'nullable|string|max:1000',
        ]);

        $transaction->update($validated);

        return redirect()->route('admin.transactions.index')
            ->with('message', 'Transaction updated successfully.');
    }

    public function destroy(Transaction $transaction)
    {
        $transaction->delete();

        return redirect()->route('admin.transactions.index')
            ->with('message', 'Transaction deleted successfully.');
    }

    public function updateStatus(Request $request, Transaction $transaction)
    {
        $validated = $request->validate([
            'status' => 'required|in:pending,processing,completed,failed',
        ]);

        $transaction->update($validated);

        return back()->with('message', 'Transaction status updated successfully.');
    }

    /**
     * Handle user topup request
     */
    public function topup(Request $request)
    {
        $image_max_upload_size = SystemSetting::getMaxUploadSize();
        try {
            $validated = $request->validate([
                'amount' => 'required|numeric|min:0.01',
                'bank_account_id' => 'required|integer|exists:bank_accounts,id',
                'evidence' => "required|image|mimes:jpeg,png,jpg,gif|max:$image_max_upload_size",
                'notes' => 'nullable|string|max:1000',
            ]);

            $user = auth()->user();

            // Handle file upload
            if ($request->hasFile('evidence')) {
                $evidencePath = $request->file('evidence')->store('transactions/evidence', 'public');
            }

            // Create transaction record
            $transaction = Transaction::create([
                'user_id' => $user->id,
                'type' => 'Tambah Baki',
                'amount' => $validated['amount'],
                'status' => 'pending',
                'reference' => Str::ulid(),
                'recipient' => 'Akaun Utama',
                'evidence' => $evidencePath ?? null,
                'notes' => $validated['notes'] ?? null,
                'bank_account_id' => $validated['bank_account_id'],
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Topup request submitted successfully',
                'transaction' => $transaction->load('user'),
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to submit topup request',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Handle user withdrawal request
     */
    public function withdrawal(Request $request)
    {
        try {
            $validated = $request->validate([
                'amount' => 'required|numeric|min:0.01',
                'bank_account_id' => 'required|integer|exists:bank_accounts,id',
                'notes' => 'nullable|string|max:1000',
            ]);

            $user = auth()->user();

            // Check if user has sufficient balance
            $currentBalance = $user->balance;
            if ($currentBalance < $validated['amount']) {
                return response()->json([
                    'success' => false,
                    'message' => 'Insufficient balance for withdrawal',
                ], 400);
            }

            // Create transaction record (negative amount for withdrawal)
            $transaction = Transaction::create([
                'user_id' => $user->id,
                'type' => 'Pengeluaran',
                'amount' => -$validated['amount'], // Negative amount for withdrawal
                'status' => 'pending',
                'reference' => Str::ulid(),
                'recipient' => 'Akaun Utama',
                'evidence' => null,
                'notes' => $validated['notes'] ?? null,
                'bank_account_id' => $validated['bank_account_id'],
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Withdrawal request submitted successfully',
                'transaction' => $transaction->load('user'),
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to submit withdrawal request',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
