<?php
require __DIR__ . '/../app/bootstrap.php';
auth_require();
require __DIR__ . '/../app/pages/_common.php';
require_perm('manage_permissions'); // admin/supervisor only

$applied = false;

if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();

  // Create attachments table if not exists
  db_exec("CREATE TABLE IF NOT EXISTS attachments (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    owner_type VARCHAR(30) NOT NULL,
    owner_id INT UNSIGNED NOT NULL,
    stored_name VARCHAR(255) NOT NULL,
    original_name VARCHAR(255) NOT NULL,
    mime VARCHAR(120) NOT NULL,
    size_bytes INT UNSIGNED NOT NULL DEFAULT 0,
    uploaded_by INT UNSIGNED NULL,
    created_at DATETIME NOT NULL,
    INDEX idx_attach_owner (owner_type, owner_id),
    CONSTRAINT fk_attach_user FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  $applied = true;
  flash_set('ok','تمت ترقية v0.3.1: إنشاء جدول المرفقات.');
  redirect(url('/index.php?page=dashboard'));
}

$title = 'ترقية v0.3.1';
$view = __DIR__ . '/../app/pages/_upgrade_view.php';
require __DIR__ . '/../app/views/layout.php';
