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

declare(strict_types=1);

require_once __DIR__ . '/../models/Solution.php';
require_once __DIR__ . '/../core/Router.php';

class SolutionController
{
    private Solution $solutionModel;
    
    public function __construct()
    {
        $this->solutionModel = new Solution();
    }
    
    /**
     * Get all solutions
     */
    public function index(array $params): array
    {
        $query = Router::getQuery();
        
        $options = [
            'status' => $query['status'] ?? 'active',
            'featured' => $query['featured'] ?? null,
            'limit' => (int) ($query['limit'] ?? 20),
            'page' => (int) ($query['page'] ?? 1)
        ];
        
        if (!empty($query['featured'])) {
            $solutions = $this->solutionModel->getFeatured($options['limit']);
            return ['solutions' => $solutions];
        }
        
        $result = $this->solutionModel->paginate($options['page'], $options['limit'], [
            'where' => ['status' => $options['status']]
        ]);
        
        return $result;
    }
    
    /**
     * Get single solution
     */
    public function show(array $params): ?array
    {
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Solution ID is required'];
        }
        
        $solution = $this->solutionModel->getWithFeatures($id);
        
        if (!$solution) {
            http_response_code(404);
            return ['error' => 'Solution not found'];
        }
        
        return $solution;
    }
    
    /**
     * Get solution by slug
     */
    public function bySlug(array $params): ?array
    {
        $slug = $params['slug'] ?? '';
        
        if (!$slug) {
            http_response_code(400);
            return ['error' => 'Slug is required'];
        }
        
        $solution = $this->solutionModel->findBySlug($slug);
        
        if (!$solution) {
            http_response_code(404);
            return ['error' => 'Solution not found'];
        }
        
        // Load features
        $sql = "SELECT * FROM features WHERE solution_id = ? AND status = 'active' ORDER BY order_position";
        $db = new Database();
        $solution['features'] = $db->fetchAll($sql, [$solution['id']]);
        
        // Load case studies
        $sql = "SELECT * FROM case_studies WHERE solution_id = ? AND published = 1 ORDER BY published_at DESC LIMIT 3";
        $solution['case_studies'] = $db->fetchAll($sql, [$solution['id']]);
        
        return $solution;
    }
    
    /**
     * Create solution (admin only)
     */
    public function create(array $params): array
    {
        AuthController::requirePermission('solutions.create');
        
        $body = Router::getBody();
        
        // Validate required fields
        $required = ['title', 'short_description'];
        foreach ($required as $field) {
            if (empty($body[$field])) {
                http_response_code(400);
                return ['error' => "Field {$field} is required"];
            }
        }
        
        // Generate slug
        $body['slug'] = $this->solutionModel->generateSlug($body['title']);
        
        // Parse JSON fields
        if (!empty($body['benefits']) && is_string($body['benefits'])) {
            $body['benefits'] = json_encode(json_decode($body['benefits'], true));
        }
        
        try {
            $id = $this->solutionModel->create($body);
            $solution = $this->solutionModel->find($id);
            
            http_response_code(201);
            return $solution;
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to create solution'];
        }
    }
    
    /**
     * Update solution (admin only)
     */
    public function update(array $params): ?array
    {
        AuthController::requirePermission('solutions.edit');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Solution ID is required'];
        }
        
        if (!$this->solutionModel->exists($id)) {
            http_response_code(404);
            return ['error' => 'Solution not found'];
        }
        
        $body = Router::getBody();
        
        // Parse JSON fields
        if (!empty($body['benefits']) && is_string($body['benefits'])) {
            $body['benefits'] = json_encode(json_decode($body['benefits'], true));
        }
        
        try {
            $this->solutionModel->update($id, $body);
            return $this->solutionModel->find($id);
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to update solution'];
        }
    }
    
    /**
     * Delete solution (admin only)
     */
    public function delete(array $params): array
    {
        AuthController::requirePermission('solutions.delete');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Solution ID is required'];
        }
        
        if (!$this->solutionModel->exists($id)) {
            http_response_code(404);
            return ['error' => 'Solution not found'];
        }
        
        try {
            $this->solutionModel->delete($id);
            return ['message' => 'Solution deleted successfully'];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to delete solution'];
        }
    }
    
    /**
     * Get featured solutions
     */
    public function featured(array $params): array
    {
        $query = Router::getQuery();
        $limit = (int) ($query['limit'] ?? 4);
        
        $solutions = $this->solutionModel->getFeatured($limit);
        
        return ['solutions' => $solutions];
    }
    
    /**
     * Get solution stats
     */
    public function stats(array $params): array
    {
        AuthController::requirePermission('solutions.view');
        
        return $this->solutionModel->getStats();
    }
}
