<?php
namespace App\Controllers;

use App\Services\SupportService;
use App\Services\AuthService;
use App\Utils\Sanitizer;

/**
 * Support Controller
 * Handles HTTP requests for CRM support logs
 */
class SupportController extends ApiController
{
    private SupportService $supportService;
    private AuthService $authService;
    
    public function __construct(SupportService $supportService, AuthService $authService)
    {
        $this->supportService = $supportService;
        $this->authService = $authService;
    }
    
    /**
     * Create a new support log
     * Both admin and CRM specialist can create
     */
    public function create()
    {
        // Check access - only admin and CRM specialist
        if (!$this->authService->canAccessSupport() && !$this->hasDelegatedCapability('support.delegated_create')) {
            $this->errorResponse('دسترسی محدود - فقط مدیر و کارشناس CRM می‌توانند پشتیبانی ثبت کنند');
        }
        
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? '');
        $channel = Sanitizer::sanitize($_POST['channel'] ?? '');
        $direction = Sanitizer::sanitize($_POST['direction'] ?? '');
        $resultNote = Sanitizer::sanitize($_POST['result_note'] ?? '');
        $createdByDidarId = $_SESSION['didar_id'] ?? '';
        
        if (empty($contactId)) {
            $this->errorResponse('شناسه لید الزامی است');
        }
        
        if (empty($channel)) {
            $this->errorResponse('نوع کانال الزامی است');
        }
        
        if (empty($direction)) {
            $this->errorResponse('جهت تماس الزامی است');
        }
        
        if (empty($resultNote)) {
            $this->errorResponse('نتیجه پشتیبانی الزامی است');
        }
        
        try {
            $id = $this->supportService->create([
                'contact_id' => $contactId,
                'channel' => $channel,
                'direction' => $direction,
                'result_note' => $resultNote,
                'created_by_didar_id' => $createdByDidarId
            ]);
            
            $this->successResponse(['id' => $id], 'پشتیبانی با موفقیت ثبت شد');
        } catch (\Exception $e) {
            \App\Utils\Logger::logError("Error creating support log", $e, ['contact_id' => $contactId]);
            $this->errorResponse('خطا در ثبت پشتیبانی: ' . $e->getMessage());
        }
    }
    
    /**
     * Update a support log
     * Only admin can update
     */
    public function update()
    {
        // Check access - only admin can edit
        if (!$this->authService->canEditSupport() && !$this->hasDelegatedCapability('support.delegated_edit')) {
            $this->errorResponse('دسترسی محدود - فقط مدیر می‌تواند پشتیبانی را ویرایش کند');
        }
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        
        if ($id <= 0) {
            $this->errorResponse('شناسه لاگ پشتیبانی الزامی است');
        }
        
        $channel = Sanitizer::sanitize($_POST['channel'] ?? '');
        $direction = Sanitizer::sanitize($_POST['direction'] ?? '');
        $resultNote = Sanitizer::sanitize($_POST['result_note'] ?? '');
        
        try {
            $this->supportService->update($id, [
                'channel' => $channel,
                'direction' => $direction,
                'result_note' => $resultNote
            ]);
            
            $this->successResponse([], 'پشتیبانی با موفقیت به‌روزرسانی شد');
        } catch (\Exception $e) {
            \App\Utils\Logger::logError("Error updating support log", $e, ['id' => $id]);
            $this->errorResponse('خطا در به‌روزرسانی پشتیبانی: ' . $e->getMessage());
        }
    }
    
    /**
     * Delete a support log
     * Only admin can delete
     */
    public function delete()
    {
        // Check access - only admin can delete
        if (!$this->authService->canEditSupport() && !$this->hasDelegatedCapability('support.delegated_delete')) {
            $this->errorResponse('دسترسی محدود - فقط مدیر می‌تواند پشتیبانی را حذف کند');
        }
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        
        if ($id <= 0) {
            $this->errorResponse('شناسه لاگ پشتیبانی الزامی است');
        }
        
        try {
            $this->supportService->delete($id);
            $this->successResponse([], 'پشتیبانی با موفقیت حذف شد');
        } catch (\Exception $e) {
            \App\Utils\Logger::logError("Error deleting support log", $e, ['id' => $id]);
            $this->errorResponse('خطا در حذف پشتیبانی: ' . $e->getMessage());
        }
    }
    
    /**
     * Get support logs for a contact
     * Both admin and CRM specialist can view
     */
    public function getByContactId()
    {
        // Check access - only admin and CRM specialist
        if (!$this->authService->canAccessSupport() && !$this->hasDelegatedCapability('support.delegated_view')) {
            $this->errorResponse('دسترسی محدود');
        }
        
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? '');
        $limit = isset($_POST['limit']) ? (int)$_POST['limit'] : 50;
        
        if (empty($contactId)) {
            $this->errorResponse('شناسه لید الزامی است');
        }
        
        try {
            $logs = $this->supportService->getByContactId($contactId, $limit);
            $this->successResponse(['support_logs' => $logs]);
        } catch (\Exception $e) {
            \App\Utils\Logger::logError("Error getting support logs", $e, ['contact_id' => $contactId]);
            $this->errorResponse('خطا در دریافت لاگ‌های پشتیبانی: ' . $e->getMessage());
        }
    }
    
    /**
     * Get a single support log
     * Both admin and CRM specialist can view
     */
    public function getById()
    {
        // Check access - only admin and CRM specialist
        if (!$this->authService->canAccessSupport() && !$this->hasDelegatedCapability('support.delegated_view')) {
            $this->errorResponse('دسترسی محدود');
        }
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        
        if ($id <= 0) {
            $this->errorResponse('شناسه لاگ پشتیبانی الزامی است');
        }
        
        try {
            $log = $this->supportService->getById($id);
            
            if (!$log) {
                $this->errorResponse('لاگ پشتیبانی یافت نشد');
            }
            
            $this->successResponse(['support_log' => $log]);
        } catch (\Exception $e) {
            \App\Utils\Logger::logError("Error getting support log", $e, ['id' => $id]);
            $this->errorResponse('خطا در دریافت لاگ پشتیبانی: ' . $e->getMessage());
        }
    }
}

