<?php
namespace Controllers\Admin;

use Core\Controller;
use Models\User;

class UserController extends Controller {
    public function index(): void {
        $this->requireRole('super-admin', 'admin');
        $page    = max(1, (int)$this->request->get('page', 1));
        $filters = [
            'search' => $this->request->get('search', ''),
            'role'   => $this->request->get('role', ''),
            'status' => $this->request->get('status', ''),
        ];
        $users = (new User())->getWithRole($this->schoolId(), $page, $filters);
        $this->view('admin/users/index', compact('users', 'filters'));
    }

    public function store(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data   = $this->request->all();
        $errors = $this->request->validate([
            'name'     => 'required|max:100',
            'email'    => 'required|email',
            'role'     => 'required|in:admin,accountant,deputy,librarian,teacher,parent',
            'password' => 'required|min:8',
        ]);
        if ($this->db->fetch("SELECT id FROM users WHERE email=?", [$data['email']])) {
            $errors['email'][] = 'Email already exists.';
        }
        if (!empty($data['password']) && $data['password'] !== ($data['password_confirmation'] ?? '')) {
            $errors['password'][] = 'Passwords do not match.';
        }
        if ($errors) {
            $this->withErrors($errors, $data);
            $this->redirect('admin/users');
            return;
        }
        $this->db->beginTransaction();
        try {
            $userId = $this->db->insert('users', [
                'school_id'  => $this->schoolId(),
                'name'       => htmlspecialchars($data['name'], ENT_QUOTES),
                'email'      => strtolower(trim($data['email'])),
                'phone'      => $data['phone'] ?? null,
                'password'   => password_hash($data['password'], PASSWORD_BCRYPT, ['cost'=>12]),
                'role'       => $data['role'],
                'is_active'  => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            if ($data['role'] === 'teacher') {
                $this->db->insert('teachers', [
                    'user_id'    => $userId,
                    'school_id'  => $this->schoolId(),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            } elseif ($data['role'] === 'parent') {
                $this->db->insert('parents', [
                    'user_id'    => $userId,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
            $this->db->commit();
            $this->logActivity('created', 'User', $userId);
            $this->withSuccess('User created successfully.');
        } catch (\Throwable $e) {
            $this->db->rollback();
            $this->withError('Failed: ' . $e->getMessage());
        }
        $this->redirect('admin/users');
    }

    public function toggle(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $user = (new User())->find((int)$id);
        if ($user) {
            $active = $user['is_active'] ? 0 : 1;
            (new User())->update((int)$id, ['is_active' => $active]);
            $this->logActivity($active ? 'activated' : 'deactivated', 'User', (int)$id);
            $this->withSuccess('User status updated.');
        }
        $this->redirect('admin/users');
    }

    public function resetPassword(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $pass    = $this->request->post('password', '');
        $confirm = $this->request->post('password_confirmation', '');
        if (strlen($pass) < 8 || $pass !== $confirm) {
            $this->withError('Password must be at least 8 characters and match confirmation.');
            $this->redirect('admin/users');
            return;
        }
        (new User())->update((int)$id, ['password' => password_hash($pass, PASSWORD_BCRYPT, ['cost'=>12])]);
        $this->logActivity('password_reset', 'User', (int)$id);
        $this->withSuccess('Password reset successfully.');
        $this->redirect('admin/users');
    }
}
