<?php

namespace Yuvayana\Acadlix\Common\Models;

use Illuminate\Database\Eloquent\Model;

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

if (!class_exists('EnrollmentSource')) {
  class EnrollmentSource extends Model
  {
    protected $table;

    protected $fillable = [
      'enrollment_id',
      'source_type', // order, subscription, free_grant
      'source_id',
      'type', // course, course-bundle, membership
      'item_id',
      'via', // user, admin
      'via_id',
      'starts_at',
      'expires_at'
    ];

    public function __construct(array $attributes = [])
    {
      parent::__construct($attributes);

      $this->table = acadlix()->helper()->acadlix_table_prefix('enrollment_sources');
    }

    public function revokeAccess($sourceType, $sourceId)
    {
      // 1. Build the base query for the target rows
      $query = $this->where('source_type', $sourceType)
        ->where('source_id', $sourceId);

      // 2. Check if the records exist before running the delete
      if (!$query->exists()) {
        return false;
      }

      // 3. Delete all matching rows (wipes out single courses, or multiple courses from a bundle)
      $query->delete();

      return true;
    }

    public function updateAccess($sourceType, $sourceId, array $values)
    {
      // Mass-updates all matching course rows tied to this source origin
      return $this->where('source_type', $sourceType)
        ->where('source_id', $sourceId)
        ->update($values);
    }
  }
}