<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class FixInvoiceOrderForeignKey extends Migration
{
    public function up()
    {
        if (! $this->db->tableExists('invoices') || ! $this->db->tableExists('orders')) {
            return;
        }

        // Relasi lama masih menunjuk lama_orders sehingga invoice baru tidak dapat dibuat.
        try {
            $this->db->query('ALTER TABLE invoices DROP FOREIGN KEY fk_invoice_order');
        } catch (\Throwable $e) {
            // Constraint mungkin belum ada pada database baru.
        }

        $this->db->query(
            'ALTER TABLE invoices ADD CONSTRAINT fk_invoice_order '
            . 'FOREIGN KEY (id_order) REFERENCES orders(id_order) ON DELETE CASCADE'
        );
    }

    public function down()
    {
        if (! $this->db->tableExists('invoices')) {
            return;
        }

        $this->db->query('ALTER TABLE invoices DROP FOREIGN KEY fk_invoice_order');
    }
}
