<?php
namespace App\Controllers;

use App\Repositories\SatisfactionRepository;
use App\Repositories\PersonRepository;
use App\Services\AuthService;
use App\Utils\Sanitizer;

class SatisfactionController extends ApiController
{
    private $satisfactionRepo;
    private $personRepo;
    private $authService;

    public function __construct(
        SatisfactionRepository $satisfactionRepo,
        PersonRepository $personRepo,
        AuthService $authService
    ) {
        $this->satisfactionRepo = $satisfactionRepo;
        $this->personRepo = $personRepo;
        $this->authService = $authService;
    }

    public function save()
    {
        if (!$this->authService->canAccessSatisfaction()) {
            $this->errorResponse('دسترسی به ثبت رضایت مشتری ندارید');
        }
        
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? '');
        $score = intval($_POST['satisfaction_score'] ?? 0);
        $note = Sanitizer::sanitize($_POST['satisfaction_note'] ?? '');
        $registeredBy = $_SESSION['didar_id'] ?? '';
        
        if (empty($contactId)) {
            $this->errorResponse('شناسه لید الزامی است');
        }
        
        if ($score < 1 || $score > 5) {
            $this->errorResponse('امتیاز رضایت باید بین 1 تا 5 باشد');
        }
        
        // Verify contact exists
        $person = $this->personRepo->findByDidarId($contactId);
        if (!$person) {
            $this->errorResponse('لید یافت نشد');
        }
        
        $this->satisfactionRepo->save($contactId, $score, $note, $registeredBy);
        $this->successResponse([], 'رضایت مشتری با موفقیت ثبت شد');
    }

    public function getSatisfactions()
    {
        if (!$this->authService->canAccessSatisfaction()) {
            $this->errorResponse('دسترسی به مشاهده رضایت مشتری ندارید');
        }
        
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? '');
        if (empty($contactId)) {
            $this->errorResponse('شناسه لید الزامی است');
        }
        
        $satisfactions = $this->satisfactionRepo->findByContact($contactId);
        $this->successResponse(['satisfactions' => $satisfactions]);
    }
}

