<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

define('DB_HOST', 'localhost');
define('DB_NAME', 'aktifperformance_portal'); // CHANGE
define('DB_USER', 'aktifperformance_portal');                 // CHANGE
define('DB_PASS', 'Emrecevik.1');                 // CHANGE

define('APP_NAME', 'TUNERSuite');
define('APP_SUB', 'ECU File portal v1');

define('BASE_URL', '/portal');
define('UPLOAD_DIR', __DIR__ . '/uploads');
define('MAX_UPLOAD_MB', 200);

function db(): PDO {
  static $pdo = null;
  if ($pdo) return $pdo;
  $pdo = new PDO(
    "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4",
    DB_USER,
    DB_PASS,
    [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
  );
  return $pdo;
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function require_role($role){
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  if (empty($_SESSION['user_id'])) {
    if ($role === 'admin') header("Location: ".BASE_URL."/admin_login.php");
    else header("Location: ".BASE_URL."/login.php");
    exit;
  }
  if (!empty($_SESSION['role']) && $_SESSION['role'] !== $role){
    // If wrong role, redirect to the correct login
    if ($role === 'admin') header("Location: ".BASE_URL."/admin_login.php");
    else header("Location: ".BASE_URL."/login.php");
    exit;
  }
}

function require_user(){ require_role('user'); }
function require_admin(){ require_role('admin'); }




function ensure_column($table, $column, $ddl){
  $pdo = db();
  $st = $pdo->prepare("SELECT COUNT(*) c FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME=?");
  $st->execute([DB_NAME, $table, $column]);
  $c = (int)($st->fetch()['c'] ?? 0);
  if ($c === 0){
    $pdo->exec("ALTER TABLE `$table` ADD COLUMN $ddl");
  }
}

function ensure_schema(){
  $pdo = db();

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE,
    password VARCHAR(255),
    role ENUM('admin','user') NOT NULL,
    created_at DATETIME
  ) ENGINE=InnoDB;
  ");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS modifications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category VARCHAR(40) NOT NULL,
    name VARCHAR(120) NOT NULL,
    credit DECIMAL(10,2) NOT NULL DEFAULT 0,
    active TINYINT(1) NOT NULL DEFAULT 1,
    sort_order INT NOT NULL DEFAULT 0
  ) ENGINE=InnoDB;
  ");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    manufacturer VARCHAR(80),
    model VARCHAR(80),
    generation VARCHAR(80),
    engine VARCHAR(80),
    ecu VARCHAR(80),
    device VARCHAR(80),
    priority ENUM('NORMAL','FAST','URGENT') NOT NULL DEFAULT 'NORMAL',
    notes TEXT,
    original_filename VARCHAR(255),
    stored_filename VARCHAR(255),
    total_credit DECIMAL(10,2) NOT NULL DEFAULT 0,
    status ENUM('PENDING','PROCESSING','COMPLETED','REJECTED') NOT NULL DEFAULT 'PENDING',
    created_at DATETIME
  ) ENGINE=InnoDB;
  ");

  // Migrations (add columns if missing)
  ensure_column('requests','admin_price', "admin_price DECIMAL(10,2) NULL AFTER total_credit");
  ensure_column('requests','payment_status', "payment_status ENUM('UNPAID','PAID') NOT NULL DEFAULT 'UNPAID' AFTER status");
  ensure_column('requests','result_original_filename', "result_original_filename VARCHAR(255) NULL AFTER stored_filename");
  ensure_column('requests','result_stored_filename', "result_stored_filename VARCHAR(255) NULL AFTER result_original_filename");
  ensure_column('requests','updated_at', "updated_at DATETIME NULL AFTER created_at");

  $pdo->exec("
  CREATE TABLE IF NOT EXISTS request_mods (
    request_id INT NOT NULL,
    mod_id INT NOT NULL,
    PRIMARY KEY (request_id, mod_id)
  ) ENGINE=InnoDB;
  ");

  if (!is_dir(UPLOAD_DIR)) @mkdir(UPLOAD_DIR, 0775, true);

  $cnt = (int)$pdo->query("SELECT COUNT(*) c FROM modifications")->fetch()['c'];
  if ($cnt === 0) {
    $seed = [
      ['STAGE','Stage 1 Performance', 1.00, 1],
      ['STAGE','Stage 2 Performance', 1.50, 2],
      ['STAGE','Stage 3 Performance', 2.50, 3],
      ['STAGE','Custom Remap', 3.00, 4],
      ['EMISSION','DPF OFF', 0.50, 10],
      ['EMISSION','EGR OFF', 0.30, 11],
      ['EMISSION','DPF/EGR OFF', 0.70, 12],
      ['EMISSION','AdBlue/SCR OFF', 0.75, 13],
      ['FEATURE','Vmax OFF', 0.20, 20],
      ['FEATURE','Pop&Bangs', 0.40, 21],
      ['FEATURE','Start/Stop OFF', 0.15, 22],
      ['FEATURE','Swirl Flaps OFF', 0.25, 23],
    ];
    $st = $pdo->prepare("INSERT INTO modifications(category,name,credit,active,sort_order) VALUES (?,?,?,?,?)");
    foreach ($seed as $s) $st->execute([$s[0],$s[1],$s[2],1,$s[3]]);
  }  // Seed demo user
  $u = $pdo->prepare("SELECT id FROM users WHERE username=? LIMIT 1");
  $u->execute(['demo']);
  if (!$u->fetch()) {
    $pwd = password_hash('123456', PASSWORD_DEFAULT);
    $pdo->prepare("INSERT INTO users(username,password,role,created_at) VALUES (?,?, 'user', NOW())")->execute(['demo',$pwd]);
  }

  // Seed admin user (change after first login)
  $a = $pdo->prepare("SELECT id FROM users WHERE username=? AND role='admin' LIMIT 1");
  $a->execute(['admin']);
  if (!$a->fetch()) {
    $pwd = password_hash('admin123', PASSWORD_DEFAULT);
    $pdo->prepare("INSERT INTO users(username,password,role,created_at) VALUES (?,?, 'admin', NOW())")->execute(['admin',$pwd]);
  }

}
