<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Helpers\Mailer;
use App\Helpers\Url;
use App\Models\User;
use App\Models\MemberProfile;
use App\Models\ProfileField;
use App\Models\Contribution;
use App\Models\ContributionType;
use App\Models\EventAttendance;
use App\Models\Message;
use App\Models\AuditLog;

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

    public function dashboard()
    {
        $userId = Auth::id();
        $profileModel = new MemberProfile();
        $contributionModel = new Contribution();
        $attendanceModel = new EventAttendance();
        $messageModel = new Message();
        $userModel = new User();

        $profile = $profileModel->findByUser($userId);
        $completionPct = $profileModel->getCompletionPercentage($userId);
        $totalContributions = $contributionModel->getTotalByUser($userId);
        $recentAttendance = $attendanceModel->getByUser($userId);
        $unreadMessages = $messageModel->getUnreadCount($userId);
        $summary = $contributionModel->getMemberSummary($userId);
        $obligations = $contributionModel->getObligations($userId);

        $totalArrears = 0;
        $unpaidObligations = [];
        foreach ($obligations as $o) {
            if (!$o->is_fully_paid) {
                $totalArrears += $o->balance;
                $unpaidObligations[] = $o;
            }
        }

        $gateways = [];
        if (class_exists('\App\Helpers\PaymentGateway')) {
            $gateways = \App\Helpers\PaymentGateway::getAvailableGateways();
        }

        $this->view('member/dashboard', [
            'profile' => $profile,
            'completionPct' => $completionPct,
            'totalContributions' => $totalContributions,
            'recentAttendance' => $recentAttendance,
            'unreadMessages' => $unreadMessages,
            'summary' => $summary,
            'totalArrears' => $totalArrears,
            'unpaidObligations' => $unpaidObligations,
            'gateways' => $gateways,
        ]);
    }

    public function profile()
    {
        $userId = Auth::id();
        $profileModel = new MemberProfile();
        $profile = $profileModel->findByUser($userId);
        $completionPct = $profileModel->getCompletionPercentage($userId);
        $userModel = new User();
        $user = $userModel->find($userId);

        $profileFieldModel = new ProfileField();
        $profileFields = $profileFieldModel->getActive();
        $profileFieldValues = $profileFieldModel->getAllFieldValuesForUser($userId);

        $this->view('member/profile', [
            'profile' => $profile,
            'completionPct' => $completionPct,
            'user' => $user,
            'profileFields' => $profileFields,
            'profileFieldValues' => $profileFieldValues,
        ]);
    }

    public function updateAvatar()
    {
        if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['error'] = 'No file uploaded';
            $this->redirect('/member/profile');
        }

        $file = $_FILES['avatar'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = array('jpg', 'jpeg', 'png', 'gif');

        if (!in_array($ext, $allowed)) {
            $_SESSION['error'] = 'Invalid file type. Allowed: jpg, jpeg, png, gif';
            $this->redirect('/member/profile');
        }

        $filename = 'avatar_' . Auth::id() . '_' . time() . '.' . $ext;
        $base = Url::getBaseUrl();
        $dest = $_SERVER['DOCUMENT_ROOT'] . $base . '/uploads/avatars/' . $filename;
        move_uploaded_file($file['tmp_name'], $dest);

        $path = '/uploads/avatars/' . $filename;
        $userModel = new User();
        $userModel->update(Auth::id(), array('avatar' => $path));

        $audit = new \App\Models\AuditLog();
        $audit->log(Auth::id(), 'profile.avatar', 'users', Auth::id(), 'Profile photo updated from member area');

        $_SESSION['success'] = 'Profile photo updated successfully';
        $this->redirect('/member/profile');
    }

    public function saveProfile()
    {
        try {
            $userId = Auth::id();
            $profileModel = new MemberProfile();
            $profile = $profileModel->findByUser($userId);

        $previousMemberValue = $_POST['previous_member'] ?? 'no';
        if (is_string($previousMemberValue)) {
            $previousMemberValue = strtolower(trim($previousMemberValue));
            $previousMemberValue = in_array($previousMemberValue, ['1', 'yes', 'true', 'on'], true) ? 1 : 0;
        } else {
            $previousMemberValue = (int)$previousMemberValue;
        }

        $data = [
            'gender' => $_POST['gender'] ?? null,
            'nationality' => $_POST['nationality'] ?? null,
            'postal_address' => $_POST['postal_address'] ?? null,
            'residential_address' => $_POST['residential_address'] ?? null,
            'mobile_phone' => $_POST['mobile_phone'] ?? null,
            'alternative_phone' => $_POST['alternative_phone'] ?? null,
            'institution_hospital' => $_POST['institution_hospital'] ?? null,
            'city_town' => $_POST['city_town'] ?? null,
            'country' => $_POST['country'] ?? null,
            'years_practice' => $_POST['years_practice'] ?? null,
            'highest_qualification' => $_POST['highest_qualification'] ?? null,
            'membership_category' => $_POST['membership_category'] ?? null,
            'previous_member' => $previousMemberValue,
            'notify_conferences' => isset($_POST['notify_conferences']) ? 1 : 0,
            'notify_workshops' => isset($_POST['notify_workshops']) ? 1 : 0,
            'notify_webinars' => isset($_POST['notify_webinars']) ? 1 : 0,
            'notify_research' => isset($_POST['notify_research']) ? 1 : 0,
            'notify_scholarships' => isset($_POST['notify_scholarships']) ? 1 : 0,
            'notify_news' => isset($_POST['notify_news']) ? 1 : 0,
            'declaration_initials' => $_POST['declaration_initials'] ?? null,
            'declaration_date' => $_POST['declaration_date'] ?? null,
        ];

        $userModel = new User();
        $userModel->update($userId, [
            'medical_council_number' => trim($_POST['medical_council_number'] ?? ''),
        ]);

        if ($profile) {
            $profileModel->update($profile->id, $data);
        } else {
            $data['user_id'] = $userId;
            $profileModel->create($data);
        }

        $profileFieldModel = new ProfileField();
        $activeFields = $profileFieldModel->getActive();
        foreach ($activeFields as $pf) {
            $val = $_POST['pf_' . $pf->field_name] ?? '';
            if ($pf->field_type === 'checkbox') {
                $val = isset($_POST['pf_' . $pf->field_name]) ? '1' : '0';
            }
            $profileFieldModel->setFieldValue($userId, $pf->id, $val);
        }

        $isComplete = $profileModel->isComplete($userId);
        $userModel->update($userId, ['profile_complete' => $isComplete ? 1 : 0]);

$_SESSION['success'] = 'Profile updated successfully';
            $this->redirect('/member/profile');
        } catch (\Exception $e) {
            error_log('saveProfile error: ' . $e->getMessage());
            $_SESSION['error'] = 'Error saving profile: ' . $e->getMessage();
            $this->redirect('/member/profile');
        }
    }

    public function members()
    {
        $search = $_GET['search'] ?? '';
        $page = max(1, (int)($_GET['page'] ?? 1));
        $viewMode = in_array($_GET['view'] ?? '', ['list', 'grid']) ? $_GET['view'] : 'grid';

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

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

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

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

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

        $profileFieldModel = new ProfileField();
        $profileFields = $profileFieldModel->getActive();
        $profileFieldValues = $profileFieldModel->getAllFieldValuesForUser($userId);

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

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

        $this->view('member/view', [
            'title' => 'Member: ' . ($user->first_name ? trim($user->first_name . ' ' . $user->last_name) : $user->name),
            'user' => $user,
            'profile' => $profile,
            'completionPct' => $completionPct,
            'profileFields' => $profileFields,
            'profileFieldValues' => $profileFieldValues,
            'contributions' => $contributions,
            'obligations' => $obligations,
            'totalContributions' => $totalContributions,
            'assignedTypes' => $assignedTypes,
            'allTypes' => $allTypes,
        ]);
    }

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

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

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

        $newStatus = $user->status === 'active' ? 'inactive' : 'active';
        $userModel->update($userId, ['status' => $newStatus]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'member.' . $newStatus, 'users', $userId, 'Member ' . ($newStatus === 'active' ? 'activated' : 'suspended'));

        $_SESSION['success'] = 'Member ' . ($newStatus === 'active' ? 'activated' : 'suspended') . ' successfully';
        $this->redirect('/members/' . $userId);
    }

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

        $userId = $params['id'] ?? null;
        $typeId = $_POST['contribution_type_id'] ?? null;
        if (!$userId || !$typeId) {
            $_SESSION['error'] = 'Invalid request';
            $this->redirect('/members/' . $userId);
        }

        $contributionTypeModel = new ContributionType();
        $contributionTypeModel->assignToMember($userId, $typeId, Auth::id());

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'contribution_type.assign', 'member_contribution_types', null, "Assigned contribution type {$typeId} to user {$userId}");

        $_SESSION['success'] = 'Contribution type assigned successfully';
        $this->redirect('/members/' . $userId);
    }

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

        $userId = $params['id'] ?? null;
        $typeId = $params['typeId'] ?? null;
        if (!$userId || !$typeId) {
            $_SESSION['error'] = 'Invalid request';
            $this->redirect('/members/' . $userId);
        }

        $contributionTypeModel = new ContributionType();
        $contributionTypeModel->unassignFromMember($userId, $typeId);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'contribution_type.unassign', 'member_contribution_types', null, "Unassigned contribution type {$typeId} from user {$userId}");

        $_SESSION['success'] = 'Contribution type removed successfully';
        $this->redirect('/members/' . $userId);
    }

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

        $recipientId = $params['id'] ?? null;
        $subject = trim($_POST['subject'] ?? '');
        $body = trim($_POST['body'] ?? '');

        if (!$recipientId || empty($subject) || empty($body)) {
            $_SESSION['error'] = 'Please fill in all fields';
            $this->redirect('/members/' . $recipientId);
        }

        $stmt = $this->db->prepare("INSERT INTO messages (sender_id, subject, body) VALUES (?, ?, ?)");
        $stmt->execute([Auth::id(), $subject, $body]);
        $messageId = $this->db->lastInsertId();

        $this->db->prepare("INSERT INTO message_recipients (message_id, recipient_id) VALUES (?, ?)")->execute([$messageId, $recipientId]);

        $_SESSION['success'] = 'Message sent successfully';
        $this->redirect('/members/' . $recipientId);
    }
}
