<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddScheduledMonthToProductions extends Migration
{
    public function up()
    {
        if (! $this->db->tableExists('productions')) {
            return;
        }

        if (! $this->db->fieldExists('scheduled_month', 'productions')) {
            $this->forge->addColumn('productions', [
                'scheduled_month' => [
                    'type' => 'DATE',
                    'null' => true,
                    'after' => 'id_order',
                ],
            ]);
            $this->db->query('ALTER TABLE productions ADD INDEX idx_productions_batch (id_order, scheduled_month)');
        }

        // Header produksi lama tetap menjadi satu batch pada bulan targetnya.
        $this->db->query("UPDATE productions p
            INNER JOIN orders o ON o.id_order = p.id_order
            SET p.scheduled_month = DATE_FORMAT(COALESCE(o.target_date, CURDATE()), '%Y-%m-01')
            WHERE p.scheduled_month IS NULL");
    }

    public function down()
    {
        if ($this->db->fieldExists('scheduled_month', 'productions')) {
            $this->forge->dropColumn('productions', 'scheduled_month');
        }
    }
}
