<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Contribution;
use App\Models\ManagementYear;
use App\Models\Project;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class ReportController extends Controller
{
    private function getFilteredData(Request $request)
    {
        $queryContributions = Contribution::query()->with(['user', 'project', 'managementYear', 'account']);
        $queryTransactions = Transaction::query()->with(['account']);

        // Apply filters
        if ($request->filled('management_year_id')) {
            $queryContributions->where('management_year_id', $request->management_year_id);
            $year = ManagementYear::find($request->management_year_id);
            if ($year) {
                $queryTransactions->whereYear('date', $year->year);
            }
        }

        if ($request->filled('project_id')) {
            $queryContributions->where('project_id', $request->project_id);
        }

        if ($request->filled('user_id')) {
            $queryContributions->where('user_id', $request->user_id);
        }

        if ($request->filled('status')) {
            $queryContributions->where('status', $request->status);
        }

        if ($request->filled('account_id')) {
            $queryContributions->where('account_id', $request->account_id);
            $queryTransactions->where('account_id', $request->account_id);
        }

        if ($request->filled('start_date')) {
            $queryContributions->whereDate('payment_date', '>=', $request->start_date);
            $queryTransactions->whereDate('date', '>=', $request->start_date);
        }

        if ($request->filled('end_date')) {
            $queryContributions->whereDate('payment_date', '<=', $request->end_date);
            $queryTransactions->whereDate('date', '<=', $request->end_date);
        }

        return [
            'queryContributions' => $queryContributions,
            'queryTransactions' => $queryTransactions
        ];
    }

    public function index(Request $request)
    {
        // Default to current month if dates are not provided
        if (!$request->filled('start_date')) {
            $request->merge(['start_date' => now()->startOfMonth()->format('Y-m-d')]);
        }
        if (!$request->filled('end_date')) {
            $request->merge(['end_date' => now()->endOfMonth()->format('Y-m-d')]);
        }

        $years = ManagementYear::orderBy('year', 'desc')->get();
        $projects = Project::all();
        $members = User::where('role', 'membre')->get();
        $accounts = Account::where('is_active', true)->get();

        $filteredData = $this->getFilteredData($request);
        $queryContributions = $filteredData['queryContributions'];
        $queryTransactions = $filteredData['queryTransactions'];

        // Total of all accounts
        $totalAccountBalance = Account::where('is_active', true)->sum('balance');

        // Statistics
        $totalContributions = (clone $queryContributions)->where('status', 'paye')->sum('amount');
        $totalPending = (clone $queryContributions)->where('status', 'non_paye')->sum('amount');
        
        $totalCredits = (clone $queryTransactions)->where('type', 'credit')->sum('amount');
        $totalDebits = (clone $queryTransactions)->where('type', 'debit')->sum('amount');

        $contributions = $queryContributions->orderBy('payment_date', 'desc')->take(100)->get();
        $transactions = $queryTransactions->orderBy('date', 'desc')->take(100)->get();

        $currency = \App\Models\Setting::get('currency', 'FCFA');

        return view('admin.reports.index', compact(
            'years', 'projects', 'members', 'accounts',
            'totalContributions', 'totalPending', 'totalCredits', 'totalDebits', 'totalAccountBalance',
            'contributions', 'transactions', 'currency'
        ));
    }

    public function exportPdf(Request $request)
    {
        // Default to current month if dates are not provided
        if (!$request->filled('start_date')) {
            $request->merge(['start_date' => now()->startOfMonth()->format('Y-m-d')]);
        }
        if (!$request->filled('end_date')) {
            $request->merge(['end_date' => now()->endOfMonth()->format('Y-m-d')]);
        }

        $filteredData = $this->getFilteredData($request);
        $contributions = $filteredData['queryContributions']->orderBy('payment_date', 'desc')->get();
        $transactions = $filteredData['queryTransactions']->orderBy('date', 'desc')->get();

        $totalContributions = $contributions->where('status', 'paye')->sum('amount');
        $totalPending = $contributions->where('status', 'non_paye')->sum('amount');
        $totalCredits = $transactions->where('type', 'credit')->sum('amount');
        $totalDebits = $transactions->where('type', 'debit')->sum('amount');
        $totalAccountBalance = Account::where('is_active', true)->sum('balance');

        $currency = \App\Models\Setting::get('currency', 'FCFA');
        
        $filters = [
            'year' => $request->management_year_id ? ManagementYear::find($request->management_year_id)?->year : null,
            'project' => $request->project_id ? Project::find($request->project_id)?->name : null,
            'member' => $request->user_id ? User::find($request->user_id)?->name : null,
            'account' => $request->account_id ? Account::find($request->account_id)?->name : null,
            'status' => $request->status,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
        ];

        $pdf = Pdf::loadView('admin.reports.export-pdf', compact(
            'contributions', 'transactions', 
            'totalContributions', 'totalPending', 'totalCredits', 'totalDebits', 'totalAccountBalance',
            'currency', 'filters'
        ));

        return $pdf->stream('rapport-financier.pdf');
    }
}
