<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\User;
use App\Models\Contribution;
use App\Models\ContributionType;
use App\Models\MemberProfile;
use App\Models\EventAttendance;
use App\Models\AuditLog;

class ReportController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function members()
    {
        if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }

        $search = $_GET['search'] ?? '';
        $page = max(1, (int)($_GET['page'] ?? 1));
        $perPage = 20;

        $userModel = new User();
        $result = $userModel->getMembersWithProfilesPage($page, $perPage, $search);

        $this->view('reports/members', [
            'members' => $result->data,
            'pagination' => $result,
            'search' => $search,
        ]);
    }

    public function member($params)
    {
        if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }

        $userId = $params['id'] ?? null;
        if (!$userId) $this->redirect('/reports/members');

        $userModel = new User();
        $user = $userModel->find($userId);
        if (!$user) {
            $_SESSION['error'] = 'Member not found';
            $this->redirect('/reports/members');
        }

        $filterTypeId = $_GET['contribution_type_id'] ?? null;

        $profileModel = new MemberProfile();
        $profile = $profileModel->findByUser($userId);

        $contributionModel = new Contribution();
        $billingMonths = $contributionModel->getBillingMonths($userId, $filterTypeId);

        $contributionTypeModel = new ContributionType();
        $assignedTypes = $contributionTypeModel->getMappedTypesForUser($userId);
        $allTypes = $contributionTypeModel->getActive();

        $attendanceModel = new EventAttendance();
        $eventsAttended = $attendanceModel->getByUser($userId);

        $contributionModel = new Contribution();
        $obligations = $contributionModel->getObligations($userId);
        $totalContributions = $contributionModel->getTotalByUser($userId);

        $this->view('reports/member', [
            'title' => 'Report: ' . ($user->first_name ? trim($user->first_name . ' ' . $user->last_name) : $user->name),
            'user' => $user,
            'profile' => $profile,
            'billingMonths' => $billingMonths,
            'assignedTypes' => $assignedTypes,
            'allTypes' => $allTypes,
            'filterTypeId' => $filterTypeId,
            'eventsAttended' => $eventsAttended,
            'obligations' => $obligations,
            'totalContributions' => $totalContributions,
        ]);
    }
}
