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

declare(strict_types=1);

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

class NewsletterController
{
    private Newsletter $newsletterModel;
    
    public function __construct()
    {
        $this->newsletterModel = new Newsletter();
    }
    
    /**
     * Subscribe to newsletter (public)
     */
    public function subscribe(array $params): array
    {
        $body = Router::getBody();
        $security = new Security();
        
        // Validate email
        if (empty($body['email']) || !$security->validateEmail($body['email'])) {
            http_response_code(400);
            return ['error' => 'Valid email is required'];
        }
        
        $email = $security->sanitize($body['email']);
        
        // Check honeypot (anti-spam)
        if (!empty($body['website'])) {
            // Honeypot field filled - likely bot
            http_response_code(400);
            return ['error' => 'Invalid request'];
        }
        
        try {
            $id = $this->newsletterModel->subscribe($email, [
                'source' => $body['source'] ?? 'website',
                'page' => $body['page'] ?? null
            ]);
            
            // Send welcome email
            $mailer = new Mailer();
            $mailer->sendNewsletterConfirmation($email);
            
            // Log event
            $security->logEvent('newsletter_subscribe', ['email' => $email]);
            
            return [
                'message' => 'Subscribed successfully',
                'id' => $id
            ];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to subscribe'];
        }
    }
    
    /**
     * Unsubscribe (public)
     */
    public function unsubscribe(array $params): array
    {
        $body = Router::getBody();
        $security = new Security();
        
        if (empty($body['email']) || !$security->validateEmail($body['email'])) {
            http_response_code(400);
            return ['error' => 'Valid email is required'];
        }
        
        $email = $security->sanitize($body['email']);
        
        try {
            $this->newsletterModel->unsubscribe($email);
            
            $security->logEvent('newsletter_unsubscribe', ['email' => $email]);
            
            return ['message' => 'Unsubscribed successfully'];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to unsubscribe'];
        }
    }
    
    /**
     * Get subscribers (admin)
     */
    public function index(array $params): array
    {
        AuthController::requirePermission('users.view');
        
        $query = Router::getQuery();
        $page = (int) ($query['page'] ?? 1);
        $limit = (int) ($query['limit'] ?? 20);
        $status = $query['status'] ?? null;
        
        return $this->newsletterModel->getSubscribers($page, $limit, $status);
    }
    
    /**
     * Get subscriber stats (admin)
     */
    public function stats(array $params): array
    {
        AuthController::requirePermission('users.view');
        
        return $this->newsletterModel->getStats();
    }
    
    /**
     * Get growth stats (admin)
     */
    public function growth(array $params): array
    {
        AuthController::requirePermission('users.view');
        
        $query = Router::getQuery();
        $days = (int) ($query['days'] ?? 30);
        
        return [
            'growth' => $this->newsletterModel->getGrowthStats($days)
        ];
    }
    
    /**
     * Delete subscriber (admin)
     */
    public function delete(array $params): array
    {
        AuthController::requirePermission('users.delete');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Subscriber ID is required'];
        }
        
        try {
            $this->newsletterModel->deleteSubscriber($id);
            return ['message' => 'Subscriber deleted successfully'];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to delete subscriber'];
        }
    }
    
    /**
     * Bulk import subscribers (admin)
     */
    public function import(array $params): array
    {
        AuthController::requirePermission('users.create');
        
        $body = Router::getBody();
        
        if (empty($body['emails']) || !is_array($body['emails'])) {
            http_response_code(400);
            return ['error' => 'Emails array is required'];
        }
        
        try {
            $results = $this->newsletterModel->bulkImport($body['emails']);
            return [
                'message' => 'Import completed',
                'results' => $results
            ];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to import subscribers'];
        }
    }
    
    /**
     * Export subscribers (admin)
     */
    public function export(array $params): array
    {
        AuthController::requirePermission('users.view');
        
        $query = Router::getQuery();
        $status = $query['status'] ?? null;
        
        $subscribers = $this->newsletterModel->export($status);
        
        return [
            'subscribers' => $subscribers,
            'count' => count($subscribers)
        ];
    }
}
