<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Migration: Support Multiple Fabrics per Order Item
 * 
 * BEST PRACTICE APPROACH:
 * - Maintain existing one-to-one relationship in tabel_detail_kain
 * - One row in tabel_detail_permintaan can have ONE PRIMARY fabric in tabel_detail_kain
 * - For multiple fabrics combination, we store additional fabrics as JSON in new field
 * 
 * ALTERNATIVE: If you want pure relational approach (one-to-many):
 * 1. Remove UNIQUE constraint on id_detail_order
 * 2. Allow multiple rows in tabel_detail_kain for same id_detail_order
 * 3. Update all queries to handle multiple rows
 * 
 * Current implementation uses HYBRID approach for backward compatibility
 */
class UpdateDetailKainForMultipleFabrics extends Migration
{
    public function up()
    {
        // Add new column to store additional fabrics as JSON
        $fields = [
            'additional_fabrics' => [
                'type' => 'TEXT',
                'null' => true,
                'comment' => 'JSON array of additional fabrics: [{"kode_jenis_kain":"KK001","meter_pemakaian":"1.5","harga_per_meter":"50000"}]'
            ],
        ];

        $this->forge->addColumn('tabel_detail_kain', $fields);

        // Note: For full relational approach (optional, commented out):
        // $this->db->query("ALTER TABLE tabel_detail_kain DROP INDEX id_detail_order");
        // This would allow multiple rows per order item, but requires extensive controller updates
    }

    public function down()
    {
        $this->forge->dropColumn('tabel_detail_kain', 'additional_fabrics');

        // If you removed UNIQUE constraint in up(), restore it:
        // $this->db->query("ALTER TABLE tabel_detail_kain ADD UNIQUE KEY id_detail_order (id_detail_order)");
    }
}
