<?php

namespace App\Http\Controllers;

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

class PaymentController extends Controller
{
    public function index(Request $request)
    {
        $query = PaymentTransaction::with(['client', 'invoice']);

        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('transaction_reference', 'like', "%{$search}%")
                  ->orWhereHas('client', function ($cq) use ($search) {
                      $cq->where('name', 'like', "%{$search}%")
                         ->orWhere('company', 'like', "%{$search}%");
                  });
            });
        }

        if ($request->filled('method')) {
            $query->where('payment_method', $request->input('method'));
        }

        $payments = $query->orderBy('paid_at', 'desc')->paginate(15);

        return view('admin.payments.index', compact('payments'));
    }

    public function exportCsv()
    {
        $fileName = 'transactions_' . date('Y-m-d') . '.csv';
        $transactions = PaymentTransaction::with(['client', 'invoice'])->orderBy('paid_at', 'desc')->get();

        $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"
        ];

        $callback = function() use($transactions) {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['TXN Reference', 'Client', 'Invoice Number', 'Amount ($)', 'Payment Method', 'Status', 'Paid Date']);

            foreach ($transactions as $txn) {
                fputcsv($file, [
                    $txn->transaction_reference,
                    $txn->client ? $txn->client->company : 'N/A',
                    $txn->invoice ? $txn->invoice->invoice_number : 'N/A',
                    number_format($txn->amount, 2),
                    $txn->payment_method,
                    $txn->status,
                    $txn->paid_at ? $txn->paid_at->format('Y-m-d H:i') : ''
                ]);
            }

            fclose($file);
        };

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