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

declare(strict_types=1);

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

class ContactController
{
    private Database $db;
    
    public function __construct()
    {
        $this->db = new Database();
    }
    
    /**
     * Submit contact form (public)
     */
    public function submit(array $params): array
    {
        $body = Router::getBody();
        $security = new Security();
        
        // Validate required fields
        $required = ['name', 'email', 'message'];
        foreach ($required as $field) {
            if (empty($body[$field])) {
                http_response_code(400);
                return ['error' => "Field {$field} is required"];
            }
        }
        
        // Validate email
        if (!$security->validateEmail($body['email'])) {
            http_response_code(400);
            return ['error' => 'Invalid email address'];
        }
        
        // Sanitize inputs
        $data = [
            'name' => $security->sanitize($body['name']),
            'email' => $security->sanitize($body['email']),
            'subject' => !empty($body['subject']) ? $security->sanitize($body['subject']) : null,
            'message' => $security->sanitize($body['message']),
            'ip_address' => $security->getClientIp(),
            'status' => 'new',
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        try {
            $id = $this->db->insert('contact_messages', $data);
            
            // Send notification email
            $this->sendContactNotification($data);
            
            http_response_code(201);
            return [
                'message' => 'Message sent successfully',
                'id' => $id
            ];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to send message'];
        }
    }
    
    /**
     * Get all contact messages (admin only)
     */
    public function index(array $params): array
    {
        AuthController::requirePermission('leads.view');
        
        $query = Router::getQuery();
        
        $status = $query['status'] ?? null;
        $page = (int) ($query['page'] ?? 1);
        $limit = (int) ($query['limit'] ?? 20);
        
        $sql = "SELECT * FROM contact_messages WHERE 1=1";
        $params = [];
        
        if ($status) {
            $sql .= " AND status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = ($page - 1) * $limit;
        
        $messages = $this->db->fetchAll($sql, $params);
        
        // Count total
        $countSql = "SELECT COUNT(*) as total FROM contact_messages WHERE 1=1";
        $countParams = [];
        
        if ($status) {
            $countSql .= " AND status = ?";
            $countParams[] = $status;
        }
        
        $totalResult = $this->db->fetchOne($countSql, $countParams);
        $total = (int) ($totalResult['total'] ?? 0);
        
        return [
            'messages' => $messages,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $limit,
                'total' => $total,
                'last_page' => (int) ceil($total / $limit)
            ]
        ];
    }
    
    /**
     * Get single contact message (admin only)
     */
    public function show(array $params): ?array
    {
        AuthController::requirePermission('leads.view');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Message ID is required'];
        }
        
        $sql = "SELECT cm.*, u.name as replied_by_name 
                FROM contact_messages cm 
                LEFT JOIN users u ON cm.replied_by = u.id 
                WHERE cm.id = ?";
        
        $message = $this->db->fetchOne($sql, [$id]);
        
        if (!$message) {
            http_response_code(404);
            return ['error' => 'Message not found'];
        }
        
        // Mark as read if new
        if ($message['status'] === 'new') {
            $this->db->update('contact_messages', ['status' => 'read'], "id = ?", [$id]);
        }
        
        return $message;
    }
    
    /**
     * Update message status (admin only)
     */
    public function updateStatus(array $params): array
    {
        AuthController::requirePermission('leads.edit');
        
        $id = (int) ($params['id'] ?? 0);
        $body = Router::getBody();
        $status = $body['status'] ?? '';
        
        $validStatuses = ['new', 'read', 'replied', 'archived'];
        
        if (!$id || !in_array($status, $validStatuses)) {
            http_response_code(400);
            return ['error' => 'Invalid message ID or status'];
        }
        
        $data = ['status' => $status];
        
        if ($status === 'replied') {
            $user = (new AuthController())->getAuthenticatedUser();
            $data['replied_by'] = $user['id'];
            $data['replied_at'] = date('Y-m-d H:i:s');
        }
        
        try {
            $this->db->update('contact_messages', $data, "id = ?", [$id]);
            return ['message' => 'Status updated successfully'];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to update status'];
        }
    }
    
    /**
     * Delete contact message (admin only)
     */
    public function delete(array $params): array
    {
        AuthController::requirePermission('leads.delete');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Message ID is required'];
        }
        
        try {
            $this->db->delete('contact_messages', "id = ?", [$id]);
            return ['message' => 'Message deleted successfully'];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to delete message'];
        }
    }
    
    /**
     * Get contact stats (admin only)
     */
    public function stats(array $params): array
    {
        AuthController::requirePermission('leads.view');
        
        $sql = "SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'new' THEN 1 ELSE 0 END) as new_count,
                    SUM(CASE WHEN status = 'read' THEN 1 ELSE 0 END) as read_count,
                    SUM(CASE WHEN status = 'replied' THEN 1 ELSE 0 END) as replied_count,
                    SUM(CASE WHEN status = 'archived' THEN 1 ELSE 0 END) as archived_count
                FROM contact_messages";
        
        $result = $this->db->fetchOne($sql);
        
        return [
            'total' => (int) $result['total'],
            'by_status' => [
                'new' => (int) $result['new_count'],
                'read' => (int) $result['read_count'],
                'replied' => (int) $result['replied_count'],
                'archived' => (int) $result['archived_count']
            ]
        ];
    }
    
    /**
     * Send contact notification email
     */
    private function sendContactNotification(array $data): void
    {
        // Log the contact
        $security = new Security();
        $security->logEvent('contact_form_submitted', [
            'email' => $data['email'],
            'name' => $data['name']
        ]);
        
        // TODO: Implement actual email sending when Mailer is configured
        // $mailer = new Mailer();
        // $mailer->sendContactNotification($data);
    }
}
