<?php

class User
{
    private $pdo;
    private static $schemaChecked = false;
    private static $hasDeletedAt = false;
    private static $hasStatus = false;
    
    public function __construct()
    {
        $this->pdo = $GLOBALS['pdo'];
    }
    
    public function create($data)
    {
        $sql = "INSERT INTO users (name, email, password, role, user_type_id, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
        $stmt = $this->pdo->prepare($sql);
        
        return $stmt->execute([
            $data['name'],
            $data['email'],
            password_hash($data['password'], PASSWORD_DEFAULT),
            $data['role'] ?? 'user',
            $data['user_type_id'] ?? null
        ]);
    }
    
    public function findByEmail($email)
    {
        $sql = "SELECT * FROM users WHERE email = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$email]);
        
        return $stmt->fetch();
    }
    
    public function findById($id)
    {
        $sql = "SELECT * FROM users WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$id]);
        
        return $stmt->fetch();
    }
    
    public function getAll()
    {
        return $this->searchPaginated();
    }

    public function countAll()
    {
        $this->checkSchema();
        $where = self::$hasDeletedAt ? "WHERE deleted_at IS NULL" : '';
        try {
            return (int)$this->pdo->query("SELECT COUNT(*) FROM users $where")->fetchColumn();
        } catch (Exception $e) {
            return 0; // fail safe
        }
    }

    public function searchPaginated($query = '', $status = 'all', $page = 1, $perPage = 10)
    {
        $this->checkSchema();
        $where = [];
        if (self::$hasDeletedAt) {
            $where[] = 'u.deleted_at IS NULL';
        }
        $params = [];
        if ($query !== '') {
            $where[] = '(u.name LIKE ? OR u.email LIKE ?)';
            $params[] = "%$query%"; $params[] = "%$query%";
        }
        if ($status !== 'all' && self::$hasStatus) {
            $where[] = 'u.status = ?';
            $params[] = $status;
        }
        $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
        $offset = ($page - 1) * $perPage;
        $sql = "SELECT SQL_CALC_FOUND_ROWS u.*, ut.name as user_type_name, ut.color as user_type_color
                FROM users u
                LEFT JOIN user_types ut ON u.user_type_id = ut.id
                $whereSql
                ORDER BY u.created_at DESC
                LIMIT $perPage OFFSET $offset";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll();
        $total = $this->pdo->query('SELECT FOUND_ROWS()')->fetchColumn();
        return [
            'data' => $rows,
            'total' => (int)$total,
            'page' => $page,
            'per_page' => $perPage,
            'pages' => (int)ceil($total / $perPage)
        ];
    }
    
    public function update($id, $data)
    {
        $this->checkSchema();
        if (self::$hasStatus) {
            $sql = "UPDATE users SET name = ?, email = ?, role = ?, user_type_id = ?, status = ?, updated_at = NOW() WHERE id = ?";
            $stmt = $this->pdo->prepare($sql);
            return $stmt->execute([
                $data['name'],
                $data['email'],
                $data['role'],
                $data['user_type_id'] ?? null,
                $data['status'] ?? 'active',
                $id
            ]);
        } else {
            $sql = "UPDATE users SET name = ?, email = ?, role = ?, user_type_id = ?, updated_at = NOW() WHERE id = ?";
            $stmt = $this->pdo->prepare($sql);
            return $stmt->execute([
                $data['name'],
                $data['email'],
                $data['role'],
                $data['user_type_id'] ?? null,
                $id
            ]);
        }
    }
    
    public function updatePassword($id, $password)
    {
        $sql = "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        
        return $stmt->execute([
            password_hash($password, PASSWORD_DEFAULT),
            $id
        ]);
    }
    
    public function delete($id)
    {
        $this->checkSchema();
        if (self::$hasDeletedAt) {
            $sql = "UPDATE users SET deleted_at = NOW()" . (self::$hasStatus ? ", status = 'inactive'" : '') . " WHERE id = ?";
            $stmt = $this->pdo->prepare($sql);
            return $stmt->execute([$id]);
        } else {
            $sql = "DELETE FROM users WHERE id = ?";
            $stmt = $this->pdo->prepare($sql);
            return $stmt->execute([$id]);
        }
    }

    public function restore($id) {
        $this->checkSchema();
        if (!self::$hasDeletedAt) return false;
        $sql = "UPDATE users SET deleted_at = NULL" . (self::$hasStatus ? ", status = 'active'" : '') . " WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute([$id]);
    }

    private function checkSchema() {
        if (self::$schemaChecked) return;
        try {
            $cols = $this->pdo->query("DESCRIBE users")->fetchAll(PDO::FETCH_COLUMN);
            self::$hasDeletedAt = in_array('deleted_at', $cols, true);
            self::$hasStatus = in_array('status', $cols, true);
        } catch (Exception $e) {
            self::$hasDeletedAt = false; self::$hasStatus = false; // fail safe
        }
        self::$schemaChecked = true;
    }
    
    public function verifyPassword($password, $hash)
    {
        return password_verify($password, $hash);
    }
}
