<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddKodeToSuplierTeknisiPelangganTables extends Migration
{
    public function up()
    {
        $this->forge->addColumn('suplier', [
            'kode_suplier' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'null'       => true,
                'after'      => 'id',
            ],
        ]);

        $this->forge->addColumn('teknisi', [
            'kode_teknisi' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'null'       => true,
                'after'      => 'id',
            ],
        ]);

        $this->forge->addColumn('pelanggan', [
            'kode_pelanggan' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'null'       => true,
                'after'      => 'id',
            ],
        ]);

        $this->db->query("UPDATE suplier SET kode_suplier = CONCAT('SUP', LPAD(id, 4, '0')) WHERE kode_suplier IS NULL OR kode_suplier = ''");
        $this->db->query("UPDATE teknisi SET kode_teknisi = CONCAT('TEK', LPAD(id, 4, '0')) WHERE kode_teknisi IS NULL OR kode_teknisi = ''");
        $this->db->query("UPDATE pelanggan SET kode_pelanggan = CONCAT('CUS', LPAD(id, 4, '0')) WHERE kode_pelanggan IS NULL OR kode_pelanggan = ''");

        $this->forge->addUniqueKey('kode_suplier', 'suplier_kode_suplier_unique');
        $this->forge->processIndexes('suplier');

        $this->forge->addUniqueKey('kode_teknisi', 'teknisi_kode_teknisi_unique');
        $this->forge->processIndexes('teknisi');

        $this->forge->addUniqueKey('kode_pelanggan', 'pelanggan_kode_pelanggan_unique');
        $this->forge->processIndexes('pelanggan');
    }

    public function down()
    {
        $this->forge->dropColumn('pelanggan', 'kode_pelanggan');
        $this->forge->dropColumn('teknisi', 'kode_teknisi');
        $this->forge->dropColumn('suplier', 'kode_suplier');
    }
}
