<?php

namespace Yuvayana\Acadlix\Common\Migrations;

use Illuminate\Database\Capsule\Manager;

defined('ABSPATH') || exit();

if (!class_exists('EnrollmentSourceMigration')) {
  class EnrollmentSourceMigration
  {
    protected $_table_name = 'enrollment_sources';
    public function up()
    {
      if (!Manager::schema()->hasTable(acadlix()->helper()->acadlix_table_prefix($this->_table_name))) {
        Manager::schema()->create(acadlix()->helper()->acadlix_table_prefix($this->_table_name), function ($table) {
          // Primary Key
          $table->bigIncrements('id');
          // Link to the main enrollment progress row
          $table->foreignId('enrollment_id')->nullable();
          $table->foreign('enrollment_id', acadlix()->helper()->acadlix_fk_prefix($this->_table_name, 'e_id'))
            ->references('id')
            ->on(acadlix()->helper()->acadlix_table_prefix('course_enrollments'))
            ->onDelete('cascade');
          // The transaction mechanism (e.g., order, subscription, free_grant)
          $table->string('source_type', 50);
          $table->unsignedBigInteger('source_id')->nullable(); // Nullable for free admin grants

          // What gave them access (e.g., course, course-bundle, membership)
          $table->string('type', 50);
          $table->unsignedBigInteger('item_id'); // ID of the specific course/bundle/membership

          // Audit Data: Who assigned this access? (e.g., user, admin)
          $table->string('via', 30)->default('user');
          $table->unsignedBigInteger('via_id')->nullable(); // User ID of student or Admin ID

          // Scheduling timestamps
          $table->timestamp('starts_at')->nullable(); // Null means immediate access
          $table->timestamp('expires_at')->nullable(); // Null means lifetime access
          $table->timestamps();
        });
      }
    }

    public function down()
    {
      Manager::schema()->dropIfExists(acadlix()->helper()->acadlix_table_prefix($this->_table_name));
    }

    public function update()
    {

    }
  }
}