<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class FixOrderItemsProductForeignKey extends Migration
{
    public function up()
    {
        $db = \Config\Database::connect();

        if (! $db->tableExists('order_items') || ! $db->tableExists('products')) {
            return;
        }

        // Relasi lama masih mengarah ke `productlama`, sehingga produk baru
        // yang tidak ada di tabel tersebut gagal disimpan ke order_items.
        try {
            $db->query('ALTER TABLE order_items DROP FOREIGN KEY order_items_ibfk_2');
        } catch (\Throwable $e) {
            // Constraint mungkin sudah pernah dihapus atau memakai nama lain.
        }

        $db->query(
            'ALTER TABLE order_items ADD CONSTRAINT fk_order_items_product '
            . 'FOREIGN KEY (id_product) REFERENCES products(id_product)'
        );
    }

    public function down()
    {
        $db = \Config\Database::connect();

        if (! $db->tableExists('order_items') || ! $db->tableExists('productlama')) {
            return;
        }

        try {
            $db->query('ALTER TABLE order_items DROP FOREIGN KEY fk_order_items_product');
        } catch (\Throwable $e) {
        }

        $db->query(
            'ALTER TABLE order_items ADD CONSTRAINT order_items_ibfk_2 '
            . 'FOREIGN KEY (id_product) REFERENCES productlama(id_product)'
        );
    }
}
