<?php

class Broker extends BaseModel
{
    public function all(?string $search = null): array
    {
        if ($search) {
            $stmt = $this->db->prepare('SELECT * FROM brokers WHERE company_name LIKE ? OR contact_name LIKE ? OR email LIKE ? OR mc_number LIKE ? ORDER BY id DESC');
            $term = "%{$search}%";
            $stmt->execute([$term, $term, $term, $term]);
            return $stmt->fetchAll();
        }

        return $this->db->query('SELECT * FROM brokers ORDER BY id DESC')->fetchAll();
    }

    public function find(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM brokers WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function create(array $data): void
    {
        $stmt = $this->db->prepare('INSERT INTO brokers (company_name, contact_name, email, phone, mc_number, address, payment_terms, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $data['company_name'], $data['contact_name'] ?: null, $data['email'] ?: null, $data['phone'] ?: null,
            $data['mc_number'] ?: null, $data['address'] ?: null, $data['payment_terms'] ?: 'Net 30', $data['status'] ?: 'active',
        ]);
    }

    public function update(int $id, array $data): void
    {
        $stmt = $this->db->prepare('UPDATE brokers SET company_name=?, contact_name=?, email=?, phone=?, mc_number=?, address=?, payment_terms=?, status=? WHERE id=?');
        $stmt->execute([
            $data['company_name'], $data['contact_name'] ?: null, $data['email'] ?: null, $data['phone'] ?: null,
            $data['mc_number'] ?: null, $data['address'] ?: null, $data['payment_terms'] ?: 'Net 30', $data['status'] ?: 'active', $id,
        ]);
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM brokers WHERE id = ?');
        $stmt->execute([$id]);
    }

    public function active(): array
    {
        return $this->db->query("SELECT id, company_name FROM brokers WHERE status = 'active' ORDER BY company_name")->fetchAll();
    }
}
