<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

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

        if ($db->tableExists('payments')) {
            try {
                $db->query('ALTER TABLE payments DROP FOREIGN KEY fk_payment_order');
            } catch (\Throwable $e) {
            }
        }

        $db->query('ALTER TABLE payments ADD CONSTRAINT fk_payment_order FOREIGN KEY (id_order) REFERENCES orders(id_order) ON DELETE CASCADE');
    }

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

        if ($db->tableExists('payments')) {
            $db->query('ALTER TABLE payments DROP FOREIGN KEY fk_payment_order');
        }

        if ($db->fieldExists('id_order', 'payments')) {
            $db->query('ALTER TABLE payments ADD CONSTRAINT fk_payment_order FOREIGN KEY (id_order) REFERENCES lama_orders(id_order) ON DELETE CASCADE');
        }
    }
}
