<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Account;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Barryvdh\DomPDF\Facade\Pdf;

class TransactionController extends Controller
{
    //========================================================
    //  GLOBAL TRANSACTIONS LIST + FILTERS
    //========================================================
    public function index(Request $request)
    {
        $query = Transaction::with(['account.user', 'account.type', 'admin'])
            ->orderBy('created_at', 'desc');

        // Filters (same as before)
        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('description', 'like', "%{$request->search}%")
                  ->orWhereHas('account', fn($a) =>
                      $a->where('account_number', 'like', "%{$request->search}%")
                    )
                  ->orWhereHas('admin', fn($u) =>
                      $u->where('name', 'like', "%{$request->search}%")
                    )
                  ->orWhereHas('account.user', fn($u) =>
                      $u->where('name', 'like', "%{$request->search}%")
                        ->orWhere('member_id', 'like', "%{$request->search}%")
                    );
            });
        }

        if ($request->type) $query->where('type', $request->type);
        if ($request->account) $query->where('account_id', $request->account);

        if ($request->member) {
            $query->whereHas('account', fn($q) => 
                $q->where('user_id', $request->member)
            );
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $transactions = $query->paginate(20);

        // Totals for summary
        $depositTotal   = (clone $query)->where('type', 'deposit')->sum('amount');
        $withdrawTotal  = (clone $query)->where('type', 'withdrawal')->sum('amount');
        $net            = $depositTotal - $withdrawTotal;

        return view('admin.transactions.index', [
            'transactions'  => $transactions,
            'depositTotal'  => $depositTotal,
            'withdrawTotal' => $withdrawTotal,
            'net'           => $net,
            'accountsList'  => Account::orderBy('account_number')->get(),
            'membersList'   => User::where('role', 'member')->orderBy('name')->get(),
        ]);
    }

    //========================================================
    //  DEPOSIT
    //========================================================
 public function deposit(Request $request, Account $account)
{
    $request->validate([
        'amount' => 'required|numeric|min:1',
        'description' => 'nullable|string|max:255',
    ]);

    $before = $account->balance;
    $after  = $before + $request->amount;

    $account->update(['balance' => $after]);

    // STORE the transaction and return the object
    $transaction = Transaction::create([
        'account_id'     => $account->id,
        'user_id'        => $account->user_id,
        'admin_id'       => Auth::id(),
        'type'           => 'deposit',
        'amount'         => $request->amount,
        'balance_before' => $before,
        'balance_after'  => $after,
        'description'    => $request->description,
    ]);

    return redirect()
        ->route('admin.transactions.receipt', $transaction->id)
        ->with('auto_download', true);
}
    //========================================================
    //  WITHDRAW
    //========================================================
    public function withdraw(Request $request, Account $account)
{
    $request->validate([
        'amount' => 'required|numeric|min:1',
        'description' => 'nullable|string|max:255',
    ]);

    if ($request->amount > $account->balance) {
        return back()->with('error', 'Insufficient balance.');
    }

    $before = $account->balance;
    $after  = $before - $request->amount;

    $account->update(['balance' => $after]);

    // STORE the transaction and return the object
$transaction = Transaction::create([
    'account_id'     => $account->id,
    'user_id'        => $account->user_id,
    'admin_id'       => Auth::id(),
    'type'           => 'Withdrawal',  // or withdrawal
    'amount'         => $request->amount,
    'balance_before' => $before,
    'balance_after'  => $after,
    'description'    => $request->description,
]);

return redirect()->route('admin.transactions.receipt', $transaction->id)
    ->with('auto_print', true);

}

    //========================================================
    //  MEMBER STATEMENT PDF — GROUPED PER ACCOUNT
    //========================================================
    public function memberStatementPdf(Request $request, User $user)
    {
        $dateFrom = $request->query('date_from', null);
        $dateTo   = $request->query('date_to', null);

        $accounts = $user->accounts()->with('type')->get();

        $data = [
            'user' => $user,
            'generated_at' => now()->toDateTimeString(),
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
            'accounts' => [],
            'memberTotals' => ['dr' => 0, 'cr' => 0, 'net' => 0],
        ];

        foreach ($accounts as $acct) {
            $q = Transaction::where('account_id', $acct->id)
                ->with('admin')
                ->orderBy('created_at', 'asc');

            if ($dateFrom) $q->whereDate('created_at', '>=', $dateFrom);
            if ($dateTo)   $q->whereDate('created_at', '<=', $dateTo);

            $txs = $q->get();

            $running = 0;
            $rows = [];
            $drTotal = 0;
            $crTotal = 0;

            foreach ($txs as $tx) {
                if ($tx->type === 'deposit') {
                    $dr = $tx->amount;
                    $cr = '';
                    $running += $dr;
                    $drTotal += $dr;
                } else {
                    $dr = '';
                    $cr = $tx->amount;
                    $running -= $cr;
                    $crTotal += $cr;
                }

                $rows[] = [
                    'date' => $tx->created_at->format('Y-m-d H:i'),
                    'description' => $tx->description ?: ucfirst($tx->type),
                    'dr' => $dr ? number_format($dr, 2) : '',
                    'cr' => $cr ? number_format($cr, 2) : '',
                    'running' => number_format($running, 2),
                    'admin' => $tx->admin->name ?? 'N/A',
                ];
            }

            $data['accounts'][] = [
                'account' => $acct,
                'transactions' => $rows,
                'totals' => [
                    'dr' => $drTotal,
                    'cr' => $crTotal,
                    'net' => $drTotal - $crTotal,
                ],
            ];

            $data['memberTotals']['dr']  += $drTotal;
            $data['memberTotals']['cr']  += $crTotal;
            $data['memberTotals']['net'] += ($drTotal - $crTotal);
        }

        $pdf = Pdf::loadView('admin.reports.member_statement', $data)
                  ->setPaper('a4', 'portrait');

        $filename = 'member_statement_' . $user->member_id . '_' . now()->format('Ymd_His') . '.pdf';

        return $pdf->download($filename);
    }


    //========================================================
// ORIGINAL "EXPORT CSV" — Detailed Transactions List
//========================================================
public function exportCsv(Request $request)
{
    $query = Transaction::with(['account.user', 'account.type', 'admin'])
        ->orderBy('created_at', 'desc');

    // Filters
    if ($request->search) {
        $query->where(function ($q) use ($request) {
            $q->where('description', 'like', "%{$request->search}%")
              ->orWhereHas('account', function ($qa) use ($request) {
                  $qa->where('account_number', 'like', "%{$request->search}%");
              })
              ->orWhereHas('account.user', function ($u) use ($request) {
                  $u->where('name', 'like', "%{$request->search}%");
              })
              ->orWhereHas('admin', function ($u) use ($request) {
                  $u->where('name', 'like', "%{$request->search}%");
              });
        });
    }

    if ($request->type)     $query->where('type', $request->type);
    if ($request->account)  $query->where('account_id', $request->account);
    if ($request->member) {
        $query->whereHas('account', fn($q) => $q->where('user_id', $request->member));
    }
    if ($request->date_from) $query->whereDate('created_at', '>=', $request->date_from);
    if ($request->date_to)   $query->whereDate('created_at', '<=', $request->date_to);

    $transactions = $query->get();

    // Headers
    $filename = 'transactions_export_' . now()->format('Ymd_His') . '.csv';
    $headers = [
        "Content-type"        => "text/csv",
        "Content-Disposition" => "attachment; filename=$filename",
        "Pragma"              => "no-cache",
        "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
        "Expires"             => "0"
    ];

    // Columns (your enriched version)
    $columns = [
        'Transaction ID',
        'Date',
        'Account Number',
        'Account Type',
        'Account Status',
        'Member Name',
        'Member Phone',
        'Member Email',
        'National ID',
        'Address',
        'Type',
        'Amount',
        'Balance Before',
        'Balance After',
        'Description',
        'Admin'
    ];

    // Build the CSV
    $callback = function() use ($transactions, $columns) {
        $file = fopen('php://output', 'w');

        // Header row
        fputcsv($file, $columns);

        foreach ($transactions as $tx) {
            $acct = $tx->account;
            $user = $acct->user ?? null;
            $type = $acct->type ?? null;

            fputcsv($file, [
                $tx->id,
                $tx->created_at->format('Y-m-d H:i'),
                $acct->account_number ?? 'N/A',
                $type->name ?? 'N/A',
                $acct->status ?? 'N/A',
                $user->name ?? 'N/A',
                $user->phone ?? 'N/A',
                $user->email ?? 'N/A',
                $user->national_id ?? 'N/A',
                $user->address ?? 'N/A',
                ucfirst($tx->type),
                $tx->amount,
                $tx->balance_before,
                $tx->balance_after,
                $tx->description,
                $tx->admin->name ?? 'N/A'
            ]);
        }

        fclose($file);
    };

    return response()->stream($callback, 200, $headers);
}

//print receipt
public function receipt($id)
{
    $transaction = Transaction::with('account.user', 'admin')->findOrFail($id);

    return view('admin.transactions.receipt', compact('transaction'));
}


}
