<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

final class QuotationDispatchRepository
{
    public function __construct(private PDO $pdo)
    {
    }

    public function find(int $id): ?array
    {
        $st = $this->pdo->prepare("SELECT q.*, p.name party_name, p.email party_email, p.phone party_phone FROM quotations q JOIN parties p ON p.id=q.party_id WHERE q.id=? LIMIT 1");
        $st->execute([$id]);
        return $st->fetch() ?: null;
    }

    public function log(int $id, string $channel, string $recipient, string $status, string $message): void
    {
        $this->pdo->prepare("INSERT INTO quotation_dispatch_logs (quotation_id, channel, recipient, status, message, sent_by, sent_at) VALUES (?,?,?,?,?,?,NOW())")
            ->execute([$id, $channel, $recipient, $status, $message, current_user_id()]);
    }

    public function markSent(int $id): void
    {
        $this->pdo->prepare("UPDATE quotations SET status=CASE WHEN status='draft' THEN 'sent' ELSE status END, sent_at=COALESCE(sent_at,NOW()) WHERE id=?")
            ->execute([$id]);
    }
}
