<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Employment documents (ID copies, contracts, certificates) attached to
 * a staff profile. Deliberately NOT served through the same public
 * UploadController::serve() route staff photos/tenant logos/menu photos
 * use — these can be genuinely sensitive personal documents, so they're
 * downloaded through a manager-authenticated UserController action
 * instead (see handle_document_upload() in app/Helpers/upload_helper.php
 * for why this also isn't the same upload path as photos: broader file
 * types, larger size cap). `original_filename` is kept separately from
 * the randomized on-disk `file_path` so a download offers a readable
 * name instead of a random string.
 */
class CreateStaffDocumentsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'user_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
            ],
            'document_type' => [
                'type'       => 'VARCHAR',
                'constraint' => 30,
                'comment'    => 'id_card, passport, contract, certificate, other',
            ],
            'file_path' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
            ],
            'original_filename' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
            ],
            'uploaded_by' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('user_id');
        $this->forge->addForeignKey('user_id', 'users', 'id', '', 'CASCADE');
        $this->forge->addForeignKey('uploaded_by', 'users', 'id', '', 'SET NULL');
        $this->forge->createTable('staff_documents');
    }

    public function down()
    {
        $this->forge->dropTable('staff_documents', true);
    }
}
