<?php

/**
 * Migration 0038 — estimates (quote → approve → invoice workflow)
 *
 * A first-class estimate a service business sends to a customer BEFORE the
 * job: line items (labor + parts), an optional vehicle (for auto/Ingine),
 * a total, and a public token URL where the customer reviews it and
 * approves (or declines). On approval the estimate converts into a normal
 * invoice (an order carrying invoice_token) so it flows through the existing
 * /invoice/{token} Stripe pay page — no new payment code.
 *
 * Additive and self-contained: one new table, nothing else touched. A shop
 * that never sends an estimate is unaffected.
 *
 * Statuses: draft → sent → approved | declined ; approved → invoiced (once
 * the invoice order is generated). invoice_order_id links back to that order.
 */

if ( ! defined( 'ABSPATH' ) ) exit;

return [
    'description' => 'Create estimates table (quote → approve-by-link → invoice)',

    'up' => [
        "CREATE TABLE IF NOT EXISTS {prefix}instinctor_estimates (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            token varchar(64) NOT NULL,
            estimate_number varchar(32) NOT NULL DEFAULT '',
            customer_id bigint(20) unsigned NULL DEFAULT NULL,
            client_name varchar(191) NOT NULL DEFAULT '',
            client_email varchar(191) NOT NULL DEFAULT '',
            client_phone varchar(64) NOT NULL DEFAULT '',
            vehicle text NULL DEFAULT NULL,
            items longtext NULL DEFAULT NULL,
            subtotal decimal(10,2) NOT NULL DEFAULT 0.00,
            tax_total decimal(10,2) NOT NULL DEFAULT 0.00,
            deposit decimal(10,2) NOT NULL DEFAULT 0.00,
            total decimal(10,2) NOT NULL DEFAULT 0.00,
            currency varchar(8) NOT NULL DEFAULT 'USD',
            status varchar(20) NOT NULL DEFAULT 'draft',
            note text NULL DEFAULT NULL,
            approval_name varchar(191) NOT NULL DEFAULT '',
            invoice_order_id bigint(20) unsigned NULL DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            sent_at datetime NULL DEFAULT NULL,
            approved_at datetime NULL DEFAULT NULL,
            declined_at datetime NULL DEFAULT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY token (token),
            KEY status (status),
            KEY customer_id (customer_id)
        ) {charset}",
    ],

    'down' => [
        "DROP TABLE IF EXISTS {prefix}instinctor_estimates",
    ],
];
