<?php

declare(strict_types=1);

namespace App\Models;

class LeadRepresentative extends BaseModel
{
    protected string $table = 'lead_representatives';

    public function findByLeadId(int $leadId): array
    {
        return $this->query(
            "SELECT * FROM {$this->table} WHERE lead_id = :lead_id ORDER BY id ASC",
            ['lead_id' => $leadId]
        );
    }

    public function saveForLead(int $leadId, array $representatives): void
    {
        $ownsTransaction = !$this->db->inTransaction();
        if ($ownsTransaction) {
            $this->db->beginTransaction();
        }
        try {
            $stmt = $this->db->prepare("DELETE FROM {$this->table} WHERE lead_id = :lead_id");
            $stmt->execute(['lead_id' => $leadId]);

            if (!empty($representatives)) {
                $insertStmt = $this->db->prepare(
                    "INSERT INTO {$this->table} (lead_id, tipo_documento, numero_documento, nombre, cargo, fecha_desde)
                     VALUES (:lead_id, :tipo_documento, :numero_documento, :nombre, :cargo, :fecha_desde)"
                );
                foreach ($representatives as $rep) {
                    $insertStmt->execute([
                        'lead_id' => $leadId,
                        'tipo_documento' => $rep['tipo_de_documento'] ?? $rep['tipo_documento'] ?? null,
                        'numero_documento' => $rep['numero_de_documento'] ?? $rep['numero_documento'] ?? null,
                        'nombre' => $rep['nombre'] ?? '',
                        'cargo' => $rep['cargo'] ?? null,
                        'fecha_desde' => $rep['fecha_desde'] ?? null,
                    ]);
                }
            }

            if ($ownsTransaction) {
                $this->db->commit();
            }
        } catch (\Exception $e) {
            if ($ownsTransaction) {
                $this->db->rollBack();
            }
            throw $e;
        }
    }
}
