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

declare(strict_types=1);

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

class Solution extends Model
{
    protected string $table = 'solutions';
    protected string $primaryKey = 'id';
    
    protected array $fillable = [
        'title',
        'slug',
        'subtitle',
        'short_description',
        'full_description',
        'problem_statement',
        'solution_description',
        'benefits',
        'icon',
        'hero_image',
        'preview_image',
        'demo_video_url',
        'features_count',
        'clients_count',
        'roi_percentage',
        'pricing_start',
        'pricing_unit',
        'meta_title',
        'meta_description',
        'order_position',
        'featured',
        'status'
    ];
    
    protected array $casts = [
        'id' => 'int',
        'features_count' => 'int',
        'clients_count' => 'int',
        'roi_percentage' => 'int',
        'pricing_start' => 'float',
        'featured' => 'bool',
        'benefits' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];
    
    /**
     * Find solution by slug
     */
    public function findBySlug(string $slug): ?array
    {
        return $this->findBy('slug', $slug);
    }
    
    /**
     * Get featured solutions
     */
    public function getFeatured(int $limit = 4): array
    {
        return $this->all([
            'where' => ['featured' => 1, 'status' => 'active'],
            'orderBy' => 'order_position',
            'order' => 'ASC',
            'limit' => $limit
        ]);
    }
    
    /**
     * Get active solutions
     */
    public function getActive(array $options = []): array
    {
        $options['where'] = array_merge($options['where'] ?? [], ['status' => 'active']);
        $options['orderBy'] = $options['orderBy'] ?? 'order_position';
        $options['order'] = $options['order'] ?? 'ASC';
        
        return $this->all($options);
    }
    
    /**
     * Get solution with features
     */
    public function getWithFeatures(int $id): ?array
    {
        $solution = $this->find($id);
        
        if (!$solution) {
            return null;
        }
        
        $sql = "SELECT * FROM features WHERE solution_id = ? AND status = 'active' ORDER BY order_position";
        $solution['features'] = $this->db->fetchAll($sql, [$id]);
        
        return $solution;
    }
    
    /**
     * Get solution with case studies
     */
    public function getWithCaseStudies(int $id): ?array
    {
        $solution = $this->find($id);
        
        if (!$solution) {
            return null;
        }
        
        $sql = "SELECT * FROM case_studies WHERE solution_id = ? AND published = 1 ORDER BY published_at DESC";
        $solution['case_studies'] = $this->db->fetchAll($sql, [$id]);
        
        return $solution;
    }
    
    /**
     * Create solution with features
     */
    public function createWithFeatures(array $data, array $features = []): int
    {
        $this->beginTransaction();
        
        try {
            $solutionId = $this->create($data);
            
            foreach ($features as $feature) {
                $feature['solution_id'] = $solutionId;
                $this->db->insert('features', $feature);
            }
            
            $this->commit();
            return $solutionId;
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }
    }
    
    /**
     * Update solution slug if title changed
     */
    public function update(int $id, array $data): bool
    {
        if (!empty($data['title']) && empty($data['slug'])) {
            $data['slug'] = $this->generateSlug($data['title'], $id);
        }
        
        return parent::update($id, $data);
    }
    
    /**
     * Generate unique slug
     */
    public function generateSlug(string $title, ?int $excludeId = null): string
    {
        $slug = $this->slugify($title);
        $originalSlug = $slug;
        $counter = 1;
        
        while (true) {
            $sql = "SELECT id FROM {$this->table} WHERE slug = ?";
            $params = [$slug];
            
            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }
            
            $existing = $this->db->fetchOne($sql, $params);
            
            if (!$existing) {
                break;
            }
            
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }
    
    /**
     * Convert title to slug
     */
    private function slugify(string $text): string
    {
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        $text = preg_replace('~[^-\w]+~', '', $text);
        $text = trim($text, '-');
        $text = preg_replace('~-+~', '-', $text);
        $text = strtolower($text);
        
        return $text ?: 'n-a';
    }
    
    /**
     * Increment client count
     */
    public function incrementClientCount(int $id): bool
    {
        $sql = "UPDATE {$this->table} SET clients_count = clients_count + 1 WHERE id = ?";
        $stmt = $this->db->query($sql, [$id]);
        return $stmt->rowCount() > 0;
    }
    
    /**
     * Get solutions for homepage
     */
    public function getForHomepage(): array
    {
        return $this->getFeatured(4);
    }
    
    /**
     * Get stats
     */
    public function getStats(): array
    {
        return [
            'total' => $this->count(),
            'active' => $this->count(['status' => 'active']),
            'featured' => $this->count(['featured' => 1, 'status' => 'active']),
            'draft' => $this->count(['status' => 'draft'])
        ];
    }
}
