<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get all assistant coaches
            $stmt = $db->query("SELECT id, username, name, phone, created_at FROM users WHERE role = 'assistant' AND is_active = 1 ORDER BY created_at DESC");
            sendJson($stmt->fetchAll());
            break;

        case 'POST':
            // Add new assistant coach
            $username = $input['username'] ?? '';
            $name = $input['name'] ?? '';
            $phone = $input['phone'] ?? '';
            $password = $input['password'] ?? substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 8);

            if (!$username || !$name) {
                sendJson(['error' => 'Username and name required'], 400);
            }

            $stmt = $db->prepare("INSERT INTO users (username, password_hash, name, role, phone) VALUES (?, ?, ?, 'assistant', ?)");
            $stmt->execute([$username, password_hash($password, PASSWORD_DEFAULT), $name, $phone]);

            sendJson([
                'success' => true,
                'id' => $db->lastInsertId(),
                'username' => $username,
                'password' => $password,
            ]);
            break;

        case 'DELETE':
            // Soft delete coach
            $id = $_GET['id'] ?? 0;
            $stmt = $db->prepare("UPDATE users SET is_active = 0 WHERE id = ? AND role = 'assistant'");
            $stmt->execute([$id]);
            sendJson(['success' => true]);
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
