<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF; // barryvdh/laravel-dompdf facade
use App\Models\Transaction;
use App\Models\Member;

class ReportsController extends Controller
{
    public function exportPdf(Request $request)
{
    $period = $request->query('period', 'month');

    // Calculate start date based on period
    $now = \Carbon\Carbon::now();
    switch ($period) {
        case 'day':
            $startDate = $now->copy()->subDay();
            break;
        case 'week':
            $startDate = $now->copy()->subWeek();
            break;
        case 'month':
            $startDate = $now->copy()->subMonth();
            break;
        case 'three_months':
            $startDate = $now->copy()->subMonths(3);
            break;
        case 'six_months':
            $startDate = $now->copy()->subMonths(6);
            break;
        case 'year':
            $startDate = $now->copy()->subYear();
            break;
        default:
            $startDate = $now->copy()->subMonth();
            break;
    }

    // Retrieve filtered transactions
    $query = \App\Models\Transaction::with('member')
        ->where('created_at', '>=', $startDate);

    // Filter by region if user is regional-treasurer
    $user = auth()->user();
    if ($user->role === 'regional-treasurer' && $user->region) {
        $query->whereHas('member.leader', function($q) use ($user) {
            $q->where('region', $user->region);
        });
    }

    $transactions = $query->latest()->get();

    $members = \App\Models\Member::all();

    // Load view and pass data including period
    $pdf = \PDF::loadView('reports.export', compact('transactions', 'members', 'period'));

    // Return PDF download response
    return $pdf->download('arise_family_report_' . date('Ymd') . '.pdf');
}
public function index()
{
    return view('reports.index');
}



    
}
