<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

$pageTitle = 'Manage Brothers';
require_once __DIR__ . '/auth.php';
require_admin();

$error = '';
$notice = '';

function identifier_rank(string $identifier): int {
    $identifier = strtoupper(trim($identifier));
    if ($identifier === '') return 999999;
    $rank = 0;
    foreach (str_split($identifier) as $char) {
        if ($char >= 'A' && $char <= 'Z') {
            $rank = ($rank * 26) + (ord($char) - 64);
        }
    }
    return $rank;
}

function sort_brothers_by_identifier(array $rows): array {
    usort($rows, function ($a, $b) {
        $rankA = identifier_rank((string)($a['identifier'] ?? ''));
        $rankB = identifier_rank((string)($b['identifier'] ?? ''));
        if ($rankA === $rankB) {
            return ((int)($a['id'] ?? 0)) <=> ((int)($b['id'] ?? 0));
        }
        return $rankA <=> $rankB;
    });
    return $rows;
}

function next_open_identifier(array $rows): string {
    foreach ($rows as $row) {
        $identifier = strtoupper(trim((string)($row['identifier'] ?? '')));
        $name = trim((string)($row['name'] ?? ''));
        $phone = trim((string)($row['phone'] ?? ''));
        if ($identifier !== '' && $name === '' && $phone === '') {
            return $identifier;
        }
    }

    $used = [];
    foreach ($rows as $row) {
        $identifier = strtoupper(trim((string)($row['identifier'] ?? '')));
        if ($identifier !== '') $used[$identifier] = true;
    }

    foreach (range('A', 'Z') as $letter) {
        if (empty($used[$letter])) return $letter;
    }

    for ($first = 'A'; $first <= 'Z'; $first++) {
        for ($second = 'A'; $second <= 'Z'; $second++) {
            $candidate = $first . $second;
            if (empty($used[$candidate])) return $candidate;
        }
    }

    return 'AAA';
}

function get_brother_by_identifier_admin(PDO $pdo, string $identifier): ?array {
    $stmt = $pdo->prepare("SELECT * FROM brothers WHERE identifier = ? LIMIT 1");
    $stmt->execute([$identifier]);
    $row = $stmt->fetch();
    return $row ?: null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';
        $id = (int)($_POST['id'] ?? 0);

        if ($action === 'save_existing') {
            $identifier = strtoupper(trim($_POST['identifier'] ?? ''));
            $name = trim($_POST['name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $sort_order = (int)($_POST['sort_order'] ?? 0);

            if ($id <= 0) {
                $error = 'Missing brother ID.';
            } elseif ($identifier === '') {
                $error = 'Identifier is required.';
            } else {
                $stmt = $pdo->prepare("UPDATE brothers SET identifier = ?, name = ?, phone = ?, sort_order = ? WHERE id = ?");
                $stmt->execute([$identifier, $name, $phone, $sort_order, $id]);
                header('Location: admin_brothers.php?notice=updated');
                exit;
            }
        }

        if ($action === 'add_new') {
            $identifier = strtoupper(trim($_POST['identifier'] ?? ''));
            $name = trim($_POST['name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $sort_order = (int)($_POST['sort_order'] ?? 0);

            if ($identifier === '') {
                $error = 'Identifier is required.';
            } else {
                $existing = get_brother_by_identifier_admin($pdo, $identifier);

                if ($existing) {
                    $existingName = trim((string)($existing['name'] ?? ''));
                    $existingPhone = trim((string)($existing['phone'] ?? ''));

                    if ($existingName !== '' || $existingPhone !== '') {
                        $error = "Identifier $identifier is already assigned. Add will not overwrite an assigned brother. Use the existing list below to edit that brother.";
                    } else {
                        $stmt = $pdo->prepare("UPDATE brothers SET name = ?, phone = ?, sort_order = ? WHERE id = ?");
                        $stmt->execute([$name, $phone, $sort_order, (int)$existing['id']]);
                        header('Location: admin_brothers.php?notice=filled');
                        exit;
                    }
                } else {
                    $stmt = $pdo->prepare("INSERT INTO brothers (identifier, name, phone, sort_order) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$identifier, $name, $phone, $sort_order]);
                    header('Location: admin_brothers.php?notice=added');
                    exit;
                }
            }
        }

        if ($action === 'clear_slot' && $id > 0) {
            $stmt = $pdo->prepare("UPDATE brothers SET name = '', phone = '' WHERE id = ?");
            $stmt->execute([$id]);
            header('Location: admin_brothers.php?notice=cleared');
            exit;
        }

        if ($action === 'delete' && $id > 0) {
            $stmt = $pdo->prepare("DELETE FROM brothers WHERE id = ?");
            $stmt->execute([$id]);
            header('Location: admin_brothers.php?notice=deleted');
            exit;
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if (!empty($_GET['notice'])) {
    $map = [
        'added' => 'Brother added.',
        'filled' => 'Open identifier filled.',
        'updated' => 'Brother updated.',
        'cleared' => 'Brother slot cleared.',
        'deleted' => 'Brother deleted.'
    ];
    $notice = $map[$_GET['notice']] ?? '';
}

try {
    $rows = $pdo->query("SELECT * FROM brothers")->fetchAll();
    $rows = sort_brothers_by_identifier($rows);
} catch (Throwable $e) {
    $rows = [];
    $error = $e->getMessage();
}

$nextIdentifier = next_open_identifier($rows);

require_once __DIR__ . '/includes/header.php';
?>

<main>
<section class="section">
<div class="container">
<div class="panel">

<h1>Manage Brothers</h1>
<p class="muted">Add new brothers, fill open identifiers, and edit existing brothers safely. Add will not overwrite a filled identifier.</p>

<?php if ($error): ?>
  <div class="error"><?php echo h($error); ?></div>
<?php endif; ?>

<?php if ($notice): ?>
  <div class="notice"><?php echo h($notice); ?></div>
<?php endif; ?>

<div class="notice">
  Suggested open identifier: <strong><?php echo h($nextIdentifier); ?></strong>
</div>

<div class="panel" style="margin-bottom:1rem;">
  <h2>Add / Fill Open Slot</h2>
  <p class="muted">Use this only to add a new brother or fill an OPEN slot. It will not overwrite someone already assigned.</p>

  <form method="post">
    <input type="hidden" name="action" value="add_new">

    <label>Identifier</label>
    <input name="identifier" required value="<?php echo h($nextIdentifier); ?>" placeholder="A, B, C, S, AA">

    <label>Name</label>
    <input name="name" placeholder="Brother name">

    <label>Phone</label>
    <input name="phone" placeholder="831-000-0000">

    <label>Sort Order</label>
    <input name="sort_order" type="number" value="0">

    <button class="btn btn-primary" type="submit">Add / Fill Open Slot</button>
  </form>
</div>

<div class="panel">
<h2>Existing Brothers</h2>
<p class="muted">Edit the individual row below and press Save. Empty placeholders show as OPEN.</p>

<?php if (!$rows): ?>
  <div class="notice">No brothers found in the database.</div>
<?php endif; ?>

<div class="brother-list">
<?php foreach ($rows as $row): ?>
  <?php
    $identifier = $row['identifier'] ?? '';
    $name = $row['name'] ?? '';
    $phone = $row['phone'] ?? '';
    $isOpen = trim((string)$name) === '' && trim((string)$phone) === '';
  ?>

  <div class="card brother-edit-card <?php echo $isOpen ? 'open-slot' : ''; ?>" style="margin-bottom:1rem;">
    <form method="post">
      <input type="hidden" name="action" value="save_existing">
      <input type="hidden" name="id" value="<?php echo h($row['id']); ?>">

      <h3>
        <?php echo h($identifier); ?>
        <?php if ($isOpen): ?>
          <span class="muted">— OPEN</span>
        <?php endif; ?>
      </h3>

      <label>Identifier</label>
      <input name="identifier" value="<?php echo h($identifier); ?>">

      <label>Name</label>
      <input name="name" value="<?php echo h($name); ?>" placeholder="Brother name">

      <label>Phone</label>
      <input name="phone" value="<?php echo h($phone); ?>" placeholder="831-000-0000">

      <label>Sort Order</label>
      <input name="sort_order" type="number" value="<?php echo h($row['sort_order'] ?? 0); ?>">

      <div class="btn-row">
        <button class="btn btn-secondary" type="submit">Save <?php echo h($identifier); ?></button>
      </div>
    </form>

    <form method="post" onsubmit="return confirm('Clear name and phone for this identifier?');">
      <input type="hidden" name="action" value="clear_slot">
      <input type="hidden" name="id" value="<?php echo h($row['id']); ?>">
      <button class="btn btn-secondary btn-small" type="submit">Clear Slot</button>
    </form>

    <form method="post" onsubmit="return confirm('Delete this identifier completely?');">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="id" value="<?php echo h($row['id']); ?>">
      <button class="btn btn-danger btn-small" type="submit">Delete <?php echo h($identifier); ?></button>
    </form>
  </div>
<?php endforeach; ?>
</div>

</div>

</div>
</div>
</section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
