<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
hw_require_auth(['admin']);

$input = json_decode(file_get_contents('php://input'), true);

$first = hw_sanitize_string($input['first_name'] ?? '');
$last = hw_sanitize_string($input['last_name'] ?? '');
$email = hw_sanitize_string($input['email'] ?? '');
$password = (string)($input['password'] ?? '');
$displayName = hw_sanitize_string($input['display_name'] ?? '');
$bio = hw_sanitize_string($input['bio'] ?? '');
$certifications = hw_sanitize_string($input['certifications'] ?? '');
$hourlyRate = $input['hourly_rate'] !== null ? (float)$input['hourly_rate'] : null;
$expertise = $input['expertise'] ?? [];

$treeBranch = hw_sanitize_string($input['tree_branch'] ?? '');
$treePosX = isset($input['tree_position_x']) ? (int)$input['tree_position_x'] : null;
$treePosY = isset($input['tree_position_y']) ? (int)$input['tree_position_y'] : null;
$profileImage = hw_sanitize_string($input['profile_image_url'] ?? '');
$yearsExperience = isset($input['years_experience']) ? (int)$input['years_experience'] : 1;
$isFeatured = isset($input['is_featured']) ? (bool)$input['is_featured'] : false;

$availability = $input['availability'] ?? null; // {timezone,start_time,end_time,working_days:[]}

if (!$first || !$last) hw_json(['success' => false, 'message' => 'First and last name are required'], 422);
if (!hw_validate_email($email)) hw_json(['success' => false, 'message' => 'Valid email is required'], 422);
if (strlen($password) < 8) hw_json(['success' => false, 'message' => 'Password must be at least 8 characters'], 422);
if (!$displayName) hw_json(['success' => false, 'message' => 'Display name is required'], 422);

try {
    $pdo = hw_db();

    // Pick a branch/position on the tree for Baobab view if not provided
    $branchRegions = [
        'roots' => ['x' => [10, 90], 'y' => [70, 90]],
        'trunk' => ['x' => [40, 60], 'y' => [55, 70]],
        'branches' => ['x' => [20, 80], 'y' => [35, 55]],
        'leaves' => ['x' => [15, 85], 'y' => [15, 35]],
        'fruits' => ['x' => [35, 65], 'y' => [10, 25]],
    ];

    if (!$treeBranch || !isset($branchRegions[$treeBranch])) {
        $counts = $pdo->query('SELECT tree_branch, COUNT(*) AS c FROM coaches GROUP BY tree_branch')->fetchAll(PDO::FETCH_KEY_PAIR);
        $treeBranch = array_keys($branchRegions)[0];
        $minCount = PHP_INT_MAX;
        foreach ($branchRegions as $branch => $_) {
            $count = isset($counts[$branch]) ? (int)$counts[$branch] : 0;
            if ($count < $minCount) {
                $minCount = $count;
                $treeBranch = $branch;
            }
        }
    }

    $region = $branchRegions[$treeBranch];
    $randInRange = function (int $min, int $max): int {
        return $min + random_int(0, max(0, $max - $min));
    };
    if ($treePosX === null) { $treePosX = $randInRange($region['x'][0], $region['x'][1]); }
    if ($treePosY === null) { $treePosY = $randInRange($region['y'][0], $region['y'][1]); }

    if (!$profileImage) {
        $profileImage = 'https://i.pravatar.cc/300?u=' . urlencode($email);
    }
    if ($yearsExperience < 1) { $yearsExperience = 1; }

    // Ensure email unique
    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        hw_json(['success' => false, 'message' => 'Email already registered'], 409);
    }

    $pdo->beginTransaction();

    // Create user
    $stmt = $pdo->prepare('INSERT INTO users (first_name, last_name, email, password_hash, status) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([$first, $last, $email, hw_hash_password($password), 'active']);
    $userId = (int)$pdo->lastInsertId();

    // Assign coach role (role_id = 3)
    $stmt = $pdo->prepare('INSERT INTO user_roles (user_id, role_id) VALUES (?, 3)');
    $stmt->execute([$userId]);

    // Create coach profile
    $expertiseJson = $expertise ? json_encode($expertise) : null;
    $stmt = $pdo->prepare('INSERT INTO coaches (user_id, display_name, bio, certifications, expertise, hourly_rate, tree_branch, tree_position_x, tree_position_y, profile_image_url, years_experience, is_featured) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $stmt->execute([
        $userId,
        $displayName,
        $bio,
        $certifications,
        $expertiseJson,
        $hourlyRate,
        $treeBranch,
        $treePosX,
        $treePosY,
        $profileImage,
        $yearsExperience,
        $isFeatured ? 1 : 0
    ]);
    $coachId = (int)$pdo->lastInsertId();

    // Optional availability seed
    if ($availability && isset($availability['working_days']) && is_array($availability['working_days'])) {
        $timezone = $availability['timezone'] ?? 'America/New_York';
        $startTime = $availability['start_time'] ?? '09:00';
        $endTime = $availability['end_time'] ?? '17:00';
        $workingDays = $availability['working_days'];

        $dayMap = [
            'Sunday' => 0,
            'Monday' => 1,
            'Tuesday' => 2,
            'Wednesday' => 3,
            'Thursday' => 4,
            'Friday' => 5,
            'Saturday' => 6
        ];

        $insertAvail = $pdo->prepare('INSERT INTO coach_availability (coach_id, weekday, start_time, end_time, timezone) VALUES (?, ?, ?, ?, ?)');
        foreach ($workingDays as $day) {
            if (isset($dayMap[$day])) {
                $insertAvail->execute([$coachId, $dayMap[$day], $startTime, $endTime, $timezone]);
            }
        }
    }

    $pdo->commit();

    hw_json([
        'success' => true,
        'message' => 'Coach created successfully',
        'coach_id' => $coachId,
        'user_id' => $userId
    ], 201);
} catch (Throwable $e) {
    if ($pdo && $pdo->inTransaction()) { $pdo->rollBack(); }
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
