<?php
// install.php
require __DIR__.'/config.php';

try {
  $pdo = db();
  $pdo->exec("SET NAMES utf8mb4");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS users (
    id BIGINT PRIMARY KEY,
    username VARCHAR(64),
    first_name VARCHAR(128),
    last_name VARCHAR(128),
    is_admin TINYINT(1) DEFAULT 0,
    test_claimed TINYINT(1) DEFAULT 0,
    test_phone VARCHAR(32) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    plan_code VARCHAR(64) NOT NULL,
    plan_title VARCHAR(255) NOT NULL,
    price INT NOT NULL,
    status ENUM('PENDING','APPROVED','REJECTED') DEFAULT 'PENDING',
    receipt_file_id VARCHAR(255) DEFAULT NULL,
    receipt_text MEDIUMTEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    approved_at TIMESTAMP NULL,
    rejected_at TIMESTAMP NULL,
    INDEX(user_id), INDEX(plan_code), INDEX(status),
    CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS configs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    plan_code VARCHAR(64) NOT NULL,
    title VARCHAR(255) NOT NULL,
    config_link TEXT DEFAULT NULL,
    config_text MEDIUMTEXT DEFAULT NULL,
    config_file_id VARCHAR(255) DEFAULT NULL,
    photo_file_id VARCHAR(255) DEFAULT NULL,
    created_by BIGINT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX(plan_code),
    CONSTRAINT fk_configs_admin FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS sales (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_id INT NOT NULL,
    user_id BIGINT NOT NULL,
    plan_code VARCHAR(64) NOT NULL,
    plan_title VARCHAR(255) NOT NULL,
    price INT NOT NULL,
    config_data MEDIUMTEXT DEFAULT NULL,
    delivered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX(order_id), INDEX(user_id),
    CONSTRAINT fk_sales_order FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT fk_sales_user  FOREIGN KEY (user_id)  REFERENCES users(id)  ON DELETE CASCADE ON UPDATE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  // ایجاد کاربر ادمین
  $admin_ids = array_map('trim', explode(',', ADMIN_IDS));
  foreach ($admin_ids as $admin_id) {
    $stmt = $pdo->prepare("INSERT IGNORE INTO users (id, is_admin) VALUES (?, 1)");
    $stmt->execute([$admin_id]);
  }

  echo "OK - Database installed successfully!";
} catch (Throwable $e) {
  http_response_code(500);
  echo "ERR: ".$e->getMessage();
}