<?php
declare(strict_types=1);

/**
 * Adds quotes.status = signed (Document Signed).
 * Fresh installs already include this in schema.sql.
 * Run: C:\xampp\php\php.exe sql/migrate_quote_signed.php
 */
$base = dirname(__DIR__);
require $base . '/app/init.php';

$db = App\Core\Database::instance();
$pdo = $db->pdo();

$col = $pdo->query(
    "SELECT COLUMN_TYPE FROM information_schema.COLUMNS
     WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'quotes' AND COLUMN_NAME = 'status'"
)->fetchColumn();

if (is_string($col) && !str_contains($col, "'signed'")) {
    $pdo->exec(
        "ALTER TABLE quotes MODIFY status ENUM('draft','pending_approval','approved','rejected','sent','signed','void') NOT NULL DEFAULT 'draft'"
    );
    echo "Added quotes.status signed\n";
} else {
    echo "quotes.status already includes signed\n";
}

$n = $pdo->exec(
    "UPDATE quotes q
     INNER JOIN portal_documents d ON d.tenant_id = q.tenant_id AND d.related_type = 'quote' AND d.related_id = q.id
     INNER JOIN signatures s ON s.document_id = d.id AND s.status = 'signed'
     SET q.status = 'signed'
     WHERE q.status IN ('sent','approved')"
);
echo 'Backfilled ' . (int) $n . " quote(s) already signed.\n";
echo "Quote signed migrate finished.\n";
