<?php
namespace App\Models;

use App\Core\Model;

class User extends Model {
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $fillable = [
        'username', 'email', 'password_hash', 'full_name', 
        'role', 'is_active', 'last_login', 'last_login_ip'
    ];
    protected $hidden = ['password_hash'];
    
    /**
     * Find user by username
     */
    public function findByUsername($username) {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE username = ? AND deleted_at IS NULL");
        $stmt->execute([$username]);
        return $stmt->fetch();
    }
    
    /**
     * Find user by email
     */
    public function findByEmail($email) {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE email = ? AND deleted_at IS NULL");
        $stmt->execute([$email]);
        return $stmt->fetch();
    }
    
    /**
     * Authenticate user
     */
    public function authenticate($username, $password) {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE username = ? AND is_active = 1 AND deleted_at IS NULL");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        
        if ($user && \Security::verifyPassword($password, $user['password_hash'])) {
            return $user;
        }
        
        return false;
    }
    
    /**
     * Update last login
     */
    public function updateLastLogin($id, $ip) {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET last_login = NOW(), last_login_ip = ? WHERE id = ?");
        return $stmt->execute([$ip, $id]);
    }
    
    /**
     * Get users by role
     */
    public function getByRole($role) {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE role = ? AND deleted_at IS NULL ORDER BY full_name ASC");
        $stmt->execute([$role]);
        return $stmt->fetchAll();
    }
    
    /**
     * Get all active users
     */
    public function getActiveUsers() {
        $stmt = $this->db->query("SELECT * FROM {$this->table} WHERE is_active = 1 AND deleted_at IS NULL ORDER BY full_name ASC");
        return $stmt->fetchAll();
    }
    
    /**
     * Create new user with password hashing - FIXED VERSION
     */
    public function createUser($data) {
        // Hash the password
        $passwordHash = \Security::hashPassword($data['password']);
        
        // Prepare only the fields that exist in the database
        $userData = [
            'username' => $data['username'],
            'email' => $data['email'],
            'password_hash' => $passwordHash,
            'full_name' => $data['full_name'],
            'role' => $data['role'],
            'is_active' => $data['is_active'] ?? 1,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        // Use the parent create method with clean data
        return $this->create($userData);
    }
    
    /**
     * Update user with optional password change - FIXED VERSION
     */
    public function updateUser($id, $data) {
        // Prepare only the fields that exist in the database
        $updateData = [
            'full_name' => $data['full_name'],
            'email' => $data['email'],
            'role' => $data['role'],
            'is_active' => $data['is_active'] ?? 0,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        // Handle password if provided
        if (isset($data['password']) && !empty($data['password'])) {
            $updateData['password_hash'] = \Security::hashPassword($data['password']);
        }
        
        return $this->update($id, $updateData);
    }
    
    /**
     * Check if user has permission (role-based)
     */
    public function hasPermission($user, $requiredRole) {
        $roles = [
            'Reviewer' => 1,
            'ImmigrationOfficer' => 2,
            'Admin' => 3,
            'SuperAdmin' => 4
        ];
        
        $userLevel = $roles[$user['role']] ?? 0;
        $requiredLevel = $roles[$requiredRole] ?? 0;
        
        return $userLevel >= $requiredLevel;
    }
    
    /**
     * Get user statistics
     */
    public function getStatistics() {
        $stats = [];
        
        // Total users
        $stmt = $this->db->query("SELECT COUNT(*) as total FROM {$this->table} WHERE deleted_at IS NULL");
        $stats['total'] = $stmt->fetch()['total'];
        
        // Users by role
        $stmt = $this->db->query("
            SELECT role, COUNT(*) as count 
            FROM {$this->table} 
            WHERE deleted_at IS NULL 
            GROUP BY role
        ");
        $stats['by_role'] = $stmt->fetchAll();
        
        // Active vs Inactive
        $stmt = $this->db->query("
            SELECT 
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active,
                SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive
            FROM {$this->table} 
            WHERE deleted_at IS NULL
        ");
        $stats['status'] = $stmt->fetch();
        
        return $stats;
    }
}