<?php

namespace App\Http\Controllers\Sms;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class SmsWalletController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $wallet = $schoolId
            ? DB::table('sms_wallets')->where('school_id', $schoolId)->first()
            : null;

        $failedThisMonth = $schoolId
            ? DB::table('sms_messages')
                ->where('school_id', $schoolId)
                ->where('status', 'failed')
                ->where('created_at', '>=', now()->startOfMonth())
                ->count()
            : 0;

        $transactions = $schoolId
            ? DB::table('sms_wallet_transactions')
                ->where('school_id', $schoolId)
                ->latest('created_at')
                ->limit(25)
                ->get()
            : collect();

        $balance = (int) ($wallet->balance ?? 0);

        $packages = DB::table('sms_packages')
            ->where('status', 'active')
            ->orderBy('sms_count')
            ->get(['id', 'title', 'sms_count', 'price'])
            ->map(fn ($p): array => [
                'id' => (int) $p->id,
                'title' => $p->title,
                'smsCount' => (int) $p->sms_count,
                'price' => (int) $p->price,
            ])->values();

        $pendingRequests = $schoolId
            ? DB::table('sms_charge_requests')
                ->where('school_id', $schoolId)
                ->where('status', 'pending')
                ->count()
            : 0;

        return Inertia::render('Sms/Wallet', [
            'isLowBalance' => $balance < 50,
            'metrics' => [
                'balance' => $balance,
                'totalUsed' => (int) ($wallet->total_used ?? 0),
                'failedThisMonth' => (int) $failedThisMonth,
            ],
            'transactions' => $transactions->map(fn ($transaction): array => [
                'description' => $transaction->description ?: $this->transactionTypeLabel($transaction->type),
                'amount' => (int) $transaction->amount,
                'balanceAfter' => (int) $transaction->balance_after,
                'createdAt' => $this->jalaliDate($transaction->created_at, true),
            ])->values(),
            'packages' => $packages,
            'pendingRequests' => (int) $pendingRequests,
        ]);
    }

    public function requestCharge(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 422);

        $data = $request->validate([
            'package_id' => ['required', 'integer'],
        ]);

        $package = DB::table('sms_packages')
            ->where('id', $data['package_id'])
            ->where('status', 'active')
            ->first();

        abort_unless($package, 422, 'بسته پیامک معتبر نیست.');

        DB::table('sms_charge_requests')->insert([
            'school_id' => $schoolId,
            'package_id' => $package->id,
            'requested_by' => $request->user()?->id,
            'sms_count' => $package->sms_count,
            'price' => $package->price,
            'status' => 'pending',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return back()->with('success', 'درخواست شارژ ارسال شد. پس از تایید مدیر سیستم، اعتبار شما افزایش می‌یابد.');
    }

    private function transactionTypeLabel(string $type): string
    {
        return match ($type) {
            'charge' => 'شارژ کیف پول',
            'manual_adjustment' => 'اصلاح دستی',
            'send_success' => 'ارسال موفق پیامک',
            'send_refund' => 'برگشت اعتبار',
            default => $type,
        };
    }
}
