<?php
require_once '../config/cors.php';
header('Content-Type: application/json');
require_once '../config/db.php';

try {
    // Create ranks table if not exists (admin can add ranks via management later)
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS ranks (
            id INT AUTO_INCREMENT PRIMARY KEY,
            rank_name VARCHAR(100) NOT NULL UNIQUE,
            sort_order INT DEFAULT 0
        )
    ");
    $stmt = $pdo->query("SELECT id, rank_name FROM ranks ORDER BY sort_order ASC, rank_name ASC");
    $ranks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($ranks)) {
        $pdo->exec("INSERT IGNORE INTO ranks (rank_name, sort_order) VALUES ('R.O', 1), ('C.R.O', 2), ('RM', 3)");
        $stmt = $pdo->query("SELECT id, rank_name FROM ranks ORDER BY sort_order ASC, rank_name ASC");
        $ranks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    echo json_encode(['status' => 'success', 'data' => $ranks]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error', 'data' => []]);
}
