<?php
namespace App\Controllers;

use App\Repositories\OperationRepository;
use App\Repositories\OperationRuleRepository;
use App\Services\OperationManagerService;
use App\Utils\Sanitizer;

class OperationManagerController extends ApiController
{
    private OperationManagerService $service;
    private OperationRepository $operations;
    private OperationRuleRepository $rules;

    public function __construct(OperationManagerService $service, OperationRepository $operations, OperationRuleRepository $rules)
    {
        $this->service = $service;
        $this->operations = $operations;
        $this->rules = $rules;
    }

    public function preview(): void
    {
        $filters = $this->readJsonArray('filters');
        $page = (int)($_POST['page'] ?? 1);
        $perPage = (int)($_POST['per_page'] ?? 50);
        $this->successResponse($this->service->preview($filters, $page, $perPage));
    }

    public function execute(): void
    {
        $filters = $this->readJsonArray('filters');
        $operation = $this->readJsonArray('operation');
        $selectedIds = $this->readJsonArray('selected_ids');
        $selectAll = (int)($_POST['select_all'] ?? 0) === 1;
        $result = $this->service->execute($filters, $operation, $selectedIds, $selectAll, (int)($_SESSION['user_id'] ?? 0), 'manual');
        $this->successResponse($result, 'Operation executed');
    }

    public function listRules(): void
    {
        $this->successResponse(['rules' => $this->rules->listRules()]);
    }

    public function getRule(): void
    {
        $id = (int)($_POST['id'] ?? $_GET['id'] ?? 0);
        $rule = $this->rules->getRule($id);
        if (!$rule) {
            $this->errorResponse('Rule not found', 404);
        }
        $this->successResponse(['rule' => $rule]);
    }

    public function saveRule(): void
    {
        $data = [
            'id' => (int)($_POST['id'] ?? 0),
            'name' => Sanitizer::sanitize($_POST['name'] ?? ''),
            'description' => Sanitizer::sanitize($_POST['description'] ?? ''),
            'is_active' => (int)($_POST['is_active'] ?? 1) === 1,
            'entity_scope' => Sanitizer::sanitize($_POST['entity_scope'] ?? 'lead'),
            'filter' => $this->readJsonArray('filter'),
            'condition' => $this->readJsonArray('condition'),
            'operation' => $this->readJsonArray('operation'),
            'schedule_type' => Sanitizer::sanitize($_POST['schedule_type'] ?? 'manual'),
            'schedule_config' => $this->readJsonArray('schedule_config'),
            'dry_run_default' => (int)($_POST['dry_run_default'] ?? 1) === 1,
        ];
        if ($data['name'] === '') {
            $this->errorResponse('Rule name is required');
        }
        $id = $this->rules->saveRule($data, (int)($_SESSION['user_id'] ?? 0));
        $this->successResponse(['id' => $id], 'Rule saved');
    }

    public function deleteRule(): void
    {
        $this->rules->deleteRule((int)($_POST['id'] ?? 0));
        $this->successResponse([], 'Rule disabled');
    }

    public function runRule(): void
    {
        $rule = $this->rules->getRule((int)($_POST['id'] ?? 0));
        if (!$rule) {
            $this->errorResponse('Rule not found', 404);
        }
        $this->successResponse($this->service->runRule($rule, (int)($_SESSION['user_id'] ?? 0), 'manual_rule'));
    }

    public function runDueRules(): void
    {
        $this->successResponse(['results' => $this->service->runDueRules()]);
    }

    public function listRuns(): void
    {
        $this->successResponse(['runs' => $this->operations->listRuns((int)($_POST['limit'] ?? 50))]);
    }

    public function getRun(): void
    {
        $run = $this->operations->getRun((int)($_POST['id'] ?? $_GET['id'] ?? 0));
        if (!$run) {
            $this->errorResponse('Run not found', 404);
        }
        $this->successResponse(['run' => $run]);
    }

    public function listPools(): void
    {
        $this->successResponse(['pools' => $this->operations->listLeadPools()]);
    }

    public function ownerHistory(): void
    {
        $contactId = Sanitizer::sanitize($_POST['contact_id'] ?? $_GET['contact_id'] ?? '');
        if ($contactId === '') {
            $this->errorResponse('contact_id is required');
        }
        $this->successResponse(['history' => $this->service->ownerHistory($contactId)]);
    }

    public function exportLeads(): void
    {
        $filters = $this->readJsonArray('filters');
        $rows = $this->service->exportAll($filters);

        $filename = 'operation_manager_export_' . date('Ymd_His') . '.csv';
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-cache, no-store');
        echo "\xEF\xBB\xBF";

        $headers = ['نام', 'موبایل', 'کد مشتری', 'مسئول فعلی', 'مسئول قبلی', 'وضعیت فروش', 'تاریخ ثبت', 'آخرین معامله', 'وضعیت آخرین معامله', 'آخرین فعالیت', 'آخرین پرداخت', 'مبلغ پرداخت', 'مخزن'];
        echo $this->csvLine($headers) . "\n";

        foreach ($rows as $row) {
            $name = trim((string)(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')));
            echo $this->csvLine([
                $name,
                (string)($row['mobile_phone'] ?? ''),
                (string)($row['customer_code'] ?? ''),
                (string)($row['owner_name'] ?? ''),
                (string)($this->resolvePreviousOwnerName($row) ?? ''),
                (string)($row['sale_status'] ?? ''),
                (string)($row['register_time_jalali'] ?? $row['register_time'] ?? ''),
                (string)($row['last_deal_at'] ?? ''),
                (string)($row['last_deal_status'] ?? ''),
                (string)($row['last_activity_at'] ?? ''),
                (string)($row['last_payment_at'] ?? ''),
                (string)($row['last_payment_amount'] ?? ''),
                (string)($row['pool_title'] ?? $row['pool_key'] ?? ''),
            ]) . "\n";
        }
        exit;
    }

    private function resolvePreviousOwnerName(array $row): string
    {
        return (string)($row['previous_owner_name'] ?? '');
    }

    private function csvLine(array $cells): string
    {
        return implode(',', array_map(static function ($cell) {
            $value = (string)$cell;
            if (strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
                return '"' . str_replace('"', '""', $value) . '"';
            }
            return $value;
        }, $cells));
    }

    private function readJsonArray(string $key): array
    {
        $raw = $_POST[$key] ?? $_REQUEST[$key] ?? '[]';
        if (is_array($raw)) {
            return $raw;
        }
        $data = json_decode((string)$raw, true);
        return is_array($data) ? $data : [];
    }
}
