﻿<?php

use App\Models\Payout;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

new class extends Component
{
    public Payout $payout;

    public string $payment_method = 'manual';

    public string $payment_reference = '';

    public string $notes = '';

    public function mount(Payout $payout): void
    {
        $this->payout = $payout->load(
            'chama',
            'fund',
            'user'
        );

        abort_unless(
            $this->payout->chama->members()
                ->where('user_id', auth()->id())
                ->where('status', 'active')
                ->whereIn('role', ['chairperson', 'admin', 'treasurer'])
                ->exists(),
            403
        );
    }

    private function availableBalance(): float
    {
        $received = Transaction::where('chama_fund_id', $this->payout->chama_fund_id)
            ->where('type', 'contribution')
            ->where('status', 'completed')
            ->sum('amount');

        $paidOut = Transaction::where('chama_fund_id', $this->payout->chama_fund_id)
            ->where('type', 'payout')
            ->where('status', 'completed')
            ->sum('amount');

        return (float) $this->payout->fund->opening_balance
            + (float) $received
            - (float) $paidOut;
    }

    public function pay(): void
    {
        abort_unless(
            $this->payout->chama->members()
                ->where('user_id', auth()->id())
                ->where('status', 'active')
                ->whereIn('role', ['chairperson', 'admin', 'treasurer'])
                ->exists(),
            403
        );

        $this->validate([
            'payment_method' => ['required', 'in:manual,mpesa,bank'],
            'payment_reference' => ['nullable', 'string', 'max:255'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        if ($this->payout->status === 'paid') {
            $this->addError(
                'payment_reference',
                'This payout has already been marked as paid.'
            );

            return;
        }

        if (! $this->payout->fund) {
            $this->addError(
                'payment_reference',
                'This payout is not assigned to a chama fund.'
            );

            return;
        }

        $availableBalance = $this->availableBalance();

        if ((float) $this->payout->amount > $availableBalance) {
            $this->addError(
                'payment_reference',
                'Insufficient fund balance. Available balance is '
                . $this->payout->fund->currency
                . ' '
                . number_format($availableBalance, 2)
                . '.'
            );

            return;
        }

        $reference = trim($this->payment_reference);

        if ($reference === '') {
            $reference = 'PAYOUT-' . now()->format('YmdHis') . '-' . $this->payout->id;
        }

        DB::transaction(function () use ($reference) {
            $this->payout->update([
                'status' => 'paid',
                'paid_at' => now(),
                'payment_method' => $this->payment_method,
                'payment_reference' => $reference,
                'notes' => $this->notes ?: null,
            ]);

            Transaction::create([
                'chama_id' => $this->payout->chama_id,
                'chama_fund_id' => $this->payout->chama_fund_id,
                'user_id' => $this->payout->user_id,
                'type' => 'payout',
                'amount' => $this->payout->amount,
                'currency' => $this->payout->fund->currency,
                'status' => 'completed',
                'payment_method' => $this->payment_method,
                'reference' => $reference,
                'external_reference' => $reference,
                'description' => 'Merry-go-round payout - Round ' . $this->payout->round_number,
                'processed_at' => now(),
            ]);
        });

        $this->payout->refresh();

        session()->flash(
            'success',
            'Payout marked as paid successfully.'
        );

        $this->redirect(
            route('chamas.payouts', $this->payout->chama->slug),
            navigate: true
        );
    }
};
?>

<div class="mx-auto max-w-2xl space-y-6">
    <div>
        <a
            href="{{ route('chamas.payouts', $payout->chama->slug) }}"
            wire:navigate
            class="text-sm font-medium text-indigo-600 hover:text-indigo-700 dark:text-indigo-400"
        >
            ← Back to Payout Schedule
        </a>

        <h1 class="mt-2 text-2xl font-bold text-zinc-900 dark:text-white">
            Mark Payout as Paid
        </h1>

        <p class="mt-1 text-sm text-zinc-600 dark:text-zinc-400">
            Round {{ $payout->round_number }} payout for {{ $payout->user->name }}
        </p>
    </div>

    <div class="rounded-xl border border-zinc-200 bg-white p-6 shadow-sm dark:border-zinc-700 dark:bg-zinc-900">
        <div class="grid gap-4 sm:grid-cols-3">
            <div>
                <p class="text-sm text-zinc-500 dark:text-zinc-400">
                    Payout Amount
                </p>

                <p class="mt-1 text-2xl font-bold text-zinc-900 dark:text-white">
                    {{ $payout->fund->currency }}
                    {{ number_format($payout->amount, 2) }}
                </p>
            </div>

            <div>
                <p class="text-sm text-zinc-500 dark:text-zinc-400">
                    Scheduled Date
                </p>

                <p class="mt-1 font-medium text-zinc-900 dark:text-white">
                    {{ $payout->scheduled_date->format('d M Y') }}
                </p>
            </div>

            <div>
                <p class="text-sm text-zinc-500 dark:text-zinc-400">
                    Fund
                </p>

                <p class="mt-1 font-medium text-zinc-900 dark:text-white">
                    {{ $payout->fund->name }}
                </p>
            </div>
        </div>
    </div>

    <form wire:submit="pay" class="space-y-6">
        <div class="rounded-xl border border-zinc-200 bg-white p-6 shadow-sm dark:border-zinc-700 dark:bg-zinc-900">
            <div>
                <label
                    for="payment_method"
                    class="mb-1 block text-sm font-medium text-zinc-700 dark:text-zinc-300"
                >
                    Payment Method
                </label>

                <select
                    id="payment_method"
                    wire:model="payment_method"
                    class="w-full rounded-lg border-zinc-300 bg-white px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-800 dark:text-white"
                >
                    <option value="manual">Manual</option>
                    <option value="mpesa">M-PESA</option>
                    <option value="bank">Bank</option>
                </select>

                @error('payment_method')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            <div class="mt-4">
                <label
                    for="payment_reference"
                    class="mb-1 block text-sm font-medium text-zinc-700 dark:text-zinc-300"
                >
                    Payment Reference
                </label>

                <input
                    id="payment_reference"
                    type="text"
                    wire:model="payment_reference"
                    placeholder="e.g. M-PESA transaction code"
                    class="w-full rounded-lg border-zinc-300 bg-white px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-800 dark:text-white"
                >

                @error('payment_reference')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            <div class="mt-4">
                <label
                    for="notes"
                    class="mb-1 block text-sm font-medium text-zinc-700 dark:text-zinc-300"
                >
                    Notes
                </label>

                <textarea
                    id="notes"
                    wire:model="notes"
                    rows="4"
                    placeholder="Optional payout notes"
                    class="w-full rounded-lg border-zinc-300 bg-white px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-800 dark:text-white"
                ></textarea>

                @error('notes')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>
        </div>

        <button
            type="submit"
            wire:loading.attr="disabled"
            class="w-full rounded-lg bg-indigo-600 px-4 py-3 text-sm font-semibold text-white hover:bg-indigo-700 disabled:opacity-50"
        >
            <span wire:loading.remove>
                Mark as Paid
            </span>

            <span wire:loading>
                Processing...
            </span>
        </button>
    </form>
</div>
