<?php

require_once '../app/Models/User.php';
require_once '../app/Models/UserType.php';

class UserController
{
    private $userModel;
    private $userTypeModel;
    
    public function __construct()
    {
        $this->userModel = new User();
        $this->userTypeModel = new UserType();
        $this->checkAuth();
    }
    
    private function checkAuth()
    {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /samanta_crm/login');
            exit;
        }
    }
    
    public function dashboard()
    {
        // Get recent users (limit 5) and total user count
        $recent = $this->userModel->searchPaginated('', 'all', 1, 5);
        $data = [
            'users' => $recent['data'] ?? [],
            'totalUsers' => $this->userModel->countAll()
        ];
        
        $this->view('dashboard', $data);
    }
    
    public function index()
    {
        $q = trim($_GET['q'] ?? '');
        $status = $_GET['status'] ?? 'all';
        $page = max(1, (int)($_GET['page'] ?? 1));
        $perPage = 10;
        $result = $this->userModel->searchPaginated($q, $status, $page, $perPage);
        $this->view('users/index', [
            'users' => $result['data'],
            'pagination' => $result,
            'filter_q' => $q,
            'filter_status' => $status
        ]);
    }
    
    public function create()
    {
        $userTypes = $this->userTypeModel->getAll(true); // Only active user types
        $this->view('users/create', ['userTypes' => $userTypes]);
    }
    
    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/users/create');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'email' => $_POST['email'] ?? '',
            'password' => $_POST['password'] ?? '',
            'role' => $_POST['role'] ?? 'user',
            'user_type_id' => !empty($_POST['user_type_id']) ? $_POST['user_type_id'] : null
        ];
        
        // Validation
        if (empty($data['name']) || empty($data['email']) || empty($data['password'])) {
            $_SESSION['error'] = 'All fields are required';
            header('Location: /samanta_crm/users/create');
            exit;
        }
        
        // Check if email already exists
        if ($this->userModel->findByEmail($data['email'])) {
            $_SESSION['error'] = 'Email already exists';
            header('Location: /samanta_crm/users/create');
            exit;
        }
        
        if ($this->userModel->create($data)) {
            $_SESSION['success'] = 'User created successfully';
        } else {
            $_SESSION['error'] = 'Failed to create user';
        }
        
        header('Location: /samanta_crm/users');
        exit;
    }
    
    public function edit($id)
    {
        $user = $this->userModel->findById($id);
        
        if (!$user) {
            $_SESSION['error'] = 'User not found';
            header('Location: /samanta_crm/users');
            exit;
        }
        
        $userTypes = $this->userTypeModel->getAll(true); // Only active user types
        $this->view('users/edit', [
            'user' => $user,
            'userTypes' => $userTypes
        ]);
    }
    
    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/users');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'email' => $_POST['email'] ?? '',
            'role' => $_POST['role'] ?? 'user',
            'user_type_id' => !empty($_POST['user_type_id']) ? $_POST['user_type_id'] : null,
            'status' => $_POST['status'] ?? 'active'
        ];
        
        if (empty($data['name']) || empty($data['email'])) {
            $_SESSION['error'] = 'Name and email are required';
            header('Location: /samanta_crm/users/' . $id . '/edit');
            exit;
        }
        
        if ($this->userModel->update($id, $data)) {
            $_SESSION['success'] = 'User updated successfully';
        } else {
            $_SESSION['error'] = 'Failed to update user';
        }
        
        header('Location: /samanta_crm/users');
        exit;
    }
    
    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/users');
            exit;
        }
        
        if ($this->userModel->delete($id)) {
            $_SESSION['success'] = 'User archived (soft deleted)';
        } else {
            $_SESSION['error'] = 'Failed to delete user';
        }
        
        header('Location: /samanta_crm/users');
        exit;
    }

    public function restore($id) {
        if ($this->userModel->restore($id)) {
            $_SESSION['success'] = 'User restored';
        } else {
            $_SESSION['error'] = 'Failed to restore user';
        }
        header('Location: /samanta_crm/users');
        exit;
    }
    
    private function view($view, $data = [])
    {
        extract($data);
        require_once "../app/Views/{$view}.php";
    }
}
