<?php

namespace App\Controllers;

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

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

    public function index()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $model = new ContributionType();
        $types = $model->all();

        $this->view('contribution_types/index', ['types' => $types]);
    }

    public function create()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $this->view('contribution_types/form', ['type' => null]);
    }

    public function store()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }

        $duration = $_POST['duration_months'] ?? '';
        $duration = $duration !== '' ? (int)$duration : null;

        $model = new ContributionType();
        $model->create([
            'name' => $_POST['name'] ?? '',
            'description' => $_POST['description'] ?? '',
            'amount' => (float)($_POST['amount'] ?? 0),
            'frequency' => $_POST['frequency'] ?? 'one-time',
            'duration_months' => $duration,
            'is_mandatory' => isset($_POST['is_mandatory']) ? 1 : 0,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'contribution_type.create', 'contribution_types', $this->db->lastInsertId(), "Created contribution type: {$_POST['name']}");

        $_SESSION['success'] = 'Contribution type created';
        $this->redirect('/contribution-types');
    }

    public function edit($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $model = new ContributionType();
        $type = $model->find($params['id'] ?? 0);
        if (!$type) {
            $_SESSION['error'] = 'Contribution type not found';
            $this->redirect('/contribution-types');
        }
        $this->view('contribution_types/form', ['type' => $type]);
    }

    public function update($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $model = new ContributionType();
        $type = $model->find($params['id'] ?? 0);
        if (!$type) {
            $_SESSION['error'] = 'Contribution type not found';
            $this->redirect('/contribution-types');
        }

        $duration = $_POST['duration_months'] ?? '';
        $duration = $duration !== '' ? (int)$duration : null;

        $model->update($type->id, [
            'name' => $_POST['name'] ?? $type->name,
            'description' => $_POST['description'] ?? $type->description,
            'amount' => (float)($_POST['amount'] ?? $type->amount),
            'frequency' => $_POST['frequency'] ?? $type->frequency,
            'duration_months' => $duration,
            'is_mandatory' => isset($_POST['is_mandatory']) ? 1 : 0,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'contribution_type.update', 'contribution_types', $type->id, "Updated contribution type: {$_POST['name']}");

        $_SESSION['success'] = 'Contribution type updated';
        $this->redirect('/contribution-types');
    }

    public function delete($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $model = new ContributionType();
        $type = $model->find($params['id'] ?? 0);
        if ($type) {
            $audit = new AuditLog();
            $audit->log(Auth::id(), 'contribution_type.delete', 'contribution_types', $type->id, "Deleted contribution type: {$type->name}");
            $model->delete($type->id);
            $_SESSION['success'] = 'Contribution type deleted';
        }
        $this->redirect('/contribution-types');
    }

    public function members($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $model = new ContributionType();
        $type = $model->find($params['id'] ?? 0);
        if (!$type) {
            $_SESSION['error'] = 'Contribution type not found';
            $this->redirect('/contribution-types');
        }

        $mapped = $model->getMappedMembers($type->id);
        $unmapped = $model->getUnmappedApprovedMembers($type->id);
        $userModel = new User();
        $allMembers = $userModel->where('approval_status', 'approved');

        $this->view('contribution_types/members', [
            'type' => $type,
            'mapped' => $mapped,
            'unmapped' => $unmapped,
            'allMembers' => $allMembers,
        ]);
    }

    public function assignMember($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $typeId = $params['id'] ?? 0;
        $userId = (int)($_POST['user_id'] ?? 0);

        $model = new ContributionType();
        $model->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'] = 'Member assigned';
        $this->redirect('/contribution-types/' . $typeId . '/members');
    }

    public function unassignMember($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $typeId = $params['id'] ?? 0;
        $userId = (int)($_POST['user_id'] ?? 0);

        $model = new ContributionType();
        $model->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'] = 'Member unassigned';
        $this->redirect('/contribution-types/' . $typeId . '/members');
    }

    public function bulkAssign($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/dashboard');
        }
        $typeId = $params['id'] ?? 0;

        $model = new ContributionType();
        $type = $model->find($typeId);
        if (!$type) {
            $_SESSION['error'] = 'Contribution type not found';
            $this->redirect('/contribution-types');
        }

        $target = $_POST['target'] ?? 'all';
        if ($target === 'all') {
            $count = $model->bulkAssignToAll($typeId, Auth::id());
            $_SESSION['success'] = "Contribution type assigned to all {$count} approved members";
        } elseif ($target === 'selected') {
            $userIds = $_POST['user_ids'] ?? [];
            if (is_string($userIds)) {
                $userIds = explode(',', $userIds);
            }
            $count = $model->bulkAssignToSelected($typeId, $userIds, Auth::id());
            $_SESSION['success'] = "Contribution type assigned to {$count} selected members";
        }

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'contribution_type.bulk_assign', 'member_contribution_types', null, "Bulk assigned contribution type #{$typeId} ({$target})");

        $this->redirect('/contribution-types/' . $typeId . '/members');
    }
}