<?php
// STEP 2F-6 ADMIN ROTATION DYNAMIC
 require_once __DIR__ . '/auth.php'; require_admin();

if (!function_exists('app_setting')) {
    function app_setting(PDO $pdo, string $key, string $default = ''): string {
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            return ($value !== false && $value !== null && $value !== '') ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

$adminRotationTitle = app_setting($pdo, 'admin_label_rotation', 'Manage Prayer Rotation');
$pageTitle = $adminRotationTitle;
 $pageTitle = $adminRotationTitle; $month=trim($_GET['month']??$_POST['month_name']??'April'); if($_SERVER['REQUEST_METHOD']==='POST'){foreach(($_POST['assigned']??[]) as $identifier=>$assigned){$stmt=$pdo->prepare("INSERT INTO rotations (month_name,owner_identifier,assigned_identifiers) VALUES (?,?,?) ON DUPLICATE KEY UPDATE assigned_identifiers=VALUES(assigned_identifiers)");$stmt->execute([$month,normalize_identifier($identifier),strtoupper(trim((string)$assigned))]);} header('Location: admin_rotation.php?month='.urlencode($month)); exit;} $brothers=$pdo->query("SELECT * FROM brothers ORDER BY sort_order ASC,id ASC")->fetchAll(); $stmt=$pdo->prepare("SELECT owner_identifier,assigned_identifiers FROM rotations WHERE month_name=?");$stmt->execute([$month]);$existing=[];foreach($stmt->fetchAll() as $row){$existing[$row['owner_identifier']]=$row['assigned_identifiers'];} $months=['April','May','June']; require_once __DIR__ . '/includes/header.php'; ?><main><section class="section"><div class="container"><div class="panel"><h1><?php echo h($adminRotationTitle); ?></h1><form method="get"><label>Month</label><select name="month" onchange="this.form.submit()"><?php foreach($months as $m): ?><option <?php echo $m===$month?'selected':''; ?>><?php echo h($m); ?></option><?php endforeach; ?></select></form><form method="post"><input type="hidden" name="month_name" value="<?php echo h($month); ?>"><table class="module-table"><tr><th>Brother</th><th>Assigned IDs</th></tr><?php foreach($brothers as $b): ?><tr><td><?php echo h($b['identifier'].' — '.$b['name']); ?><?php if(!empty($b['phone'])): ?><br><span class="muted"><?php echo h($b['phone']); ?></span><?php endif; ?></td><td><input name="assigned[<?php echo h($b['identifier']); ?>]" value="<?php echo h($existing[$b['identifier']]??''); ?>"></td></tr><?php endforeach; ?></table><button class="btn btn-primary">Save Rotation</button></form></div></div></section></main><?php require_once __DIR__ . '/includes/footer.php'; ?>
