<?php
namespace App\Services;

use App\Repositories\SupportRepository;
use App\Models\Support;
use App\Utils\Logger;

/**
 * Support Service
 * Business logic for CRM support logs
 */
class SupportService
{
    private SupportRepository $supportRepo;
    
    public function __construct(SupportRepository $supportRepo)
    {
        $this->supportRepo = $supportRepo;
    }
    
    /**
     * Create a new support log
     * Both admin and CRM specialist can create
     */
    public function create(array $data): int
    {
        $support = new Support([
            'contact_didar_id' => $data['contact_id'] ?? '',
            'channel' => $data['channel'] ?? 'call',
            'direction' => $data['direction'] ?? 'incoming',
            'result_note' => $data['result_note'] ?? '',
            'created_by_didar_id' => $data['created_by_didar_id'] ?? ''
        ]);
        
        // Validate required fields
        if (empty($support->contact_didar_id)) {
            throw new \Exception('شناسه لید الزامی است');
        }
        
        if (empty($support->channel)) {
            throw new \Exception('نوع کانال الزامی است');
        }
        
        if (empty($support->direction)) {
            throw new \Exception('جهت تماس الزامی است');
        }
        
        if (empty($support->result_note)) {
            throw new \Exception('نتیجه پشتیبانی الزامی است');
        }
        
        if (empty($support->created_by_didar_id)) {
            throw new \Exception('شناسه کاربر الزامی است');
        }
        
        // Validate channel
        $validChannels = ['call', 'chat', 'visit', 'email'];
        if (!in_array($support->channel, $validChannels)) {
            throw new \Exception('نوع کانال نامعتبر است');
        }
        
        // Validate direction
        $validDirections = ['incoming', 'outgoing'];
        if (!in_array($support->direction, $validDirections)) {
            throw new \Exception('جهت تماس نامعتبر است');
        }
        
        try {
            $id = $this->supportRepo->create($support);
            
            Logger::logInfo('Support log created', [
                'id' => $id,
                'contact_id' => $support->contact_didar_id,
                'channel' => $support->channel,
                'direction' => $support->direction,
                'created_by' => $support->created_by_didar_id
            ]);
            
            return $id;
        } catch (\Exception $e) {
            Logger::logError('Failed to create support log', $e, [
                'contact_id' => $support->contact_didar_id
            ]);
            throw $e;
        }
    }
    
    /**
     * Update a support log
     * Only admin can update
     */
    public function update(int $id, array $data): bool
    {
        $existing = $this->supportRepo->getById($id);
        
        if (!$existing) {
            throw new \Exception('لاگ پشتیبانی یافت نشد');
        }
        
        $support = new Support([
            'id' => $id,
            'contact_didar_id' => $existing->contact_didar_id,
            'channel' => $data['channel'] ?? $existing->channel,
            'direction' => $data['direction'] ?? $existing->direction,
            'result_note' => $data['result_note'] ?? $existing->result_note,
            'created_by_didar_id' => $existing->created_by_didar_id
        ]);
        
        // Validate
        if (empty($support->channel) || empty($support->direction) || empty($support->result_note)) {
            throw new \Exception('فیلدهای الزامی نمی‌توانند خالی باشند');
        }
        
        try {
            $result = $this->supportRepo->update($support);
            
            Logger::logInfo('Support log updated', [
                'id' => $id,
                'contact_id' => $support->contact_didar_id
            ]);
            
            return $result;
        } catch (\Exception $e) {
            Logger::logError('Failed to update support log', $e, ['id' => $id]);
            throw $e;
        }
    }
    
    /**
     * Delete a support log
     * Only admin can delete
     */
    public function delete(int $id): bool
    {
        try {
            $result = $this->supportRepo->delete($id);
            
            Logger::logInfo('Support log deleted', ['id' => $id]);
            
            return $result;
        } catch (\Exception $e) {
            Logger::logError('Failed to delete support log', $e, ['id' => $id]);
            throw $e;
        }
    }
    
    /**
     * Get support logs for a contact
     */
    public function getByContactId(string $contactId, int $limit = 50): array
    {
        try {
            $logs = $this->supportRepo->getByContactId($contactId, $limit);
            
            return array_map(function($log) {
                return $log->toArray();
            }, $logs);
        } catch (\Exception $e) {
            Logger::logError('Failed to get support logs', $e, ['contact_id' => $contactId]);
            throw $e;
        }
    }
    
    /**
     * Get a single support log
     */
    public function getById(int $id): ?array
    {
        try {
            $log = $this->supportRepo->getById($id);
            return $log ? $log->toArray() : null;
        } catch (\Exception $e) {
            Logger::logError('Failed to get support log', $e, ['id' => $id]);
            throw $e;
        }
    }
}

