<?php

declare(strict_types=1);

namespace App\Models;

class LeadProduct extends BaseModel
{
    protected string $table = 'lead_products';

    public function attach(int $leadId, int $productId): void
    {
        $exists = $this->queryOne(
            "SELECT 1 FROM {$this->table} WHERE lead_id = :lid AND product_id = :pid",
            ['lid' => $leadId, 'pid' => $productId]
        );

        if (!$exists) {
            $this->execute(
                "INSERT INTO {$this->table} (lead_id, product_id) VALUES (:lid, :pid)",
                ['lid' => $leadId, 'pid' => $productId]
            );
        }
    }

    public function detach(int $leadId, int $productId): void
    {
        $this->execute(
            "DELETE FROM {$this->table} WHERE lead_id = :lid AND product_id = :pid",
            ['lid' => $leadId, 'pid' => $productId]
        );
    }

    public function getByLeadId(int $leadId): array
    {
        return $this->query(
            "SELECT p.* FROM products p
             INNER JOIN {$this->table} lp ON p.id = lp.product_id
             WHERE lp.lead_id = :lid
             ORDER BY p.name",
            ['lid' => $leadId]
        );
    }

    public function getTopProducts(int $limit = 5): array
    {
        $limit = max(1, $limit);
        return $this->query(
            "SELECT p.id, p.name, p.category, COUNT(lp.lead_id) as lead_count
             FROM products p
             INNER JOIN {$this->table} lp ON p.id = lp.product_id
             WHERE p.status = 'active'
             GROUP BY p.id, p.name, p.category
             ORDER BY lead_count DESC
             LIMIT {$limit}"
        );
    }
}
