<?php

namespace Yuvayana\Acadlix\Common\Migrations;

use Illuminate\Database\Capsule\Manager;

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

if (!class_exists('CourseEnrollmentMigration')) {
  class CourseEnrollmentMigration
  {
    protected $_table_name = 'course_enrollments';
    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');

          // Foreign Keys / Relations
          $table->unsignedBigInteger('user_id');
          $table->unsignedBigInteger('course_id');
          $table->unsignedBigInteger('course_section_content_id')->nullable();

          // Metrics & Status
          $table->integer('progress_percent')->default(0);
          $table->string('status')->default('active'); // active, suspended, completed, expired

          // User Behavior Time Tracking
          $table->timestamp('started_at')->nullable();
          $table->timestamp('completed_at')->nullable();

          // Standard Laravel Timestamps
          $table->timestamps();

          // Indexes for Performance Optimization
          $table->index('user_id', acadlix()->helper()->acadlix_index_prefix($this->_table_name, 'user_id'));
          $table->index('course_id', acadlix()->helper()->acadlix_index_prefix($this->_table_name, 'course_id'));
          $table->index('course_section_content_id', acadlix()->helper()->acadlix_index_prefix($this->_table_name, 'course_section_content_id'));

          // CRITICAL: Prevent duplicate enrollment records for the same user + course combination
          $table->unique(['user_id', 'course_id'], acadlix()->helper()->acadlix_index_prefix($this->_table_name, 'user_course_unique'));
        });
      }
    }

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

    public function update()
    {

    }
  }
}