<?php
/**
 * ZLO Platform - Media Model
 */

declare(strict_types=1);

require_once __DIR__ . '/../core/Model.php';

class Media extends Model
{
    protected string $table = 'media';
    protected string $primaryKey = 'id';
    
    /**
     * Get media by type
     */
    public function getByType(string $type, int $page = 1, int $limit = 20): array
    {
        $sql = "SELECT m.*, u.name as uploaded_by_name 
                FROM {$this->table} m 
                LEFT JOIN users u ON m.uploaded_by = u.id 
                WHERE m.file_type = ? 
                ORDER BY m.created_at DESC";
        
        return $this->paginate($sql, [$type], $page, $limit);
    }
    
    /**
     * Get media by user
     */
    public function getByUser(int $userId, int $page = 1, int $limit = 20): array
    {
        $sql = "SELECT m.*, u.name as uploaded_by_name 
                FROM {$this->table} m 
                LEFT JOIN users u ON m.uploaded_by = u.id 
                WHERE m.uploaded_by = ? 
                ORDER BY m.created_at DESC";
        
        return $this->paginate($sql, [$userId], $page, $limit);
    }
    
    /**
     * Search media
     */
    public function search(string $query, int $page = 1, int $limit = 20): array
    {
        $sql = "SELECT m.*, u.name as uploaded_by_name 
                FROM {$this->table} m 
                LEFT JOIN users u ON m.uploaded_by = u.id 
                WHERE m.file_name LIKE ? OR m.original_name LIKE ? OR m.alt_text LIKE ? 
                ORDER BY m.created_at DESC";
        
        $searchTerm = "%{$query}%";
        $params = [$searchTerm, $searchTerm, $searchTerm];
        
        return $this->paginate($sql, $params, $page, $limit);
    }
    
    /**
     * Increment usage count
     */
    public function incrementUsage(int $id): bool
    {
        return $this->db->query(
            "UPDATE {$this->table} SET usage_count = usage_count + 1 WHERE id = ?",
            [$id]
        );
    }
    
    /**
     * Decrement usage count
     */
    public function decrementUsage(int $id): bool
    {
        return $this->db->query(
            "UPDATE {$this->table} SET usage_count = GREATEST(0, usage_count - 1) WHERE id = ?",
            [$id]
        );
    }
    
    /**
     * Get unused media
     */
    public function getUnused(int $days = 30): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM {$this->table} 
             WHERE usage_count = 0 AND created_at < DATE_SUB(NOW(), INTERVAL ? DAY) 
             ORDER BY created_at ASC",
            [$days]
        );
    }
    
    /**
     * Get total storage used
     */
    public function getTotalStorage(): int
    {
        $result = $this->db->fetchOne("SELECT SUM(file_size) as total FROM {$this->table}");
        return (int) ($result['total'] ?? 0);
    }
    
    /**
     * Get storage by type
     */
    public function getStorageByType(): array
    {
        return $this->db->fetchAll(
            "SELECT file_type, SUM(file_size) as total_size, COUNT(*) as count 
             FROM {$this->table} 
             GROUP BY file_type"
        );
    }
    
    /**
     * Create media record
     */
    public function createMedia(array $data): int
    {
        return $this->create([
            'file_name' => $data['file_name'],
            'original_name' => $data['original_name'],
            'file_path' => $data['file_path'],
            'file_type' => $data['file_type'],
            'mime_type' => $data['mime_type'] ?? null,
            'file_size' => $data['file_size'] ?? 0,
            'dimensions' => $data['dimensions'] ?? null,
            'alt_text' => $data['alt_text'] ?? null,
            'uploaded_by' => $data['uploaded_by'] ?? null,
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }
    
    /**
     * Update alt text
     */
    public function updateAltText(int $id, string $altText): bool
    {
        return $this->update($id, ['alt_text' => $altText]);
    }
    
    /**
     * Get recent uploads
     */
    public function getRecent(int $limit = 10, ?string $type = null): array
    {
        $sql = "SELECT m.*, u.name as uploaded_by_name 
                FROM {$this->table} m 
                LEFT JOIN users u ON m.uploaded_by = u.id 
                WHERE 1=1";
        
        $params = [];
        
        if ($type) {
            $sql .= " AND m.file_type = ?";
            $params[] = $type;
        }
        
        $sql .= " ORDER BY m.created_at DESC LIMIT ?";
        $params[] = $limit;
        
        return $this->db->fetchAll($sql, $params);
    }
}
