<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_admin();

$pageTitle = 'Platform Settings Center';
$notice = '';
$error = '';

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;
        }
    }
}

if (!function_exists('save_app_setting')) {
    function save_app_setting(PDO $pdo, string $key, string $value): void {
        $stmt = $pdo->prepare("
            INSERT INTO app_settings (setting_key, setting_value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ");
        $stmt->execute([$key, $value]);
    }
}

function ps_upload_branding(string $field, string $current): string {
    if (empty($_FILES[$field]['name']) || empty($_FILES[$field]['tmp_name'])) {
        return $current;
    }

    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $original = basename($_FILES[$field]['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return $current;
    }

    $dir = __DIR__ . '/uploads/branding';
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }

    $safeBase = preg_replace('/[^a-zA-Z0-9_-]/', '_', pathinfo($original, PATHINFO_FILENAME));
    $filename = $safeBase . '_' . date('Ymd_His') . '.' . $ext;
    $target = $dir . '/' . $filename;

    if (move_uploaded_file($_FILES[$field]['tmp_name'], $target)) {
        return 'uploads/branding/' . $filename;
    }

    return $current;
}

$themes = [
    'royal_dark' => [
        'label' => 'Royal Dark',
        'background' => '#0b1220',
        'foreground' => '#eef4ff',
        'accent' => '#d4af37',
        'secondary' => '#6a0dad',
        'panel' => '#121c2e'
    ],
    'ocean_blue' => [
        'label' => 'Ocean Blue',
        'background' => '#071827',
        'foreground' => '#eef9ff',
        'accent' => '#22d3ee',
        'secondary' => '#2563eb',
        'panel' => '#102a43'
    ],
    'olive_branch' => [
        'label' => 'Olive Branch',
        'background' => '#10180f',
        'foreground' => '#f2f8ed',
        'accent' => '#a3b18a',
        'secondary' => '#588157',
        'panel' => '#1b2a1a'
    ],
    'fire_gold' => [
        'label' => 'Fire Gold',
        'background' => '#1a0d05',
        'foreground' => '#fff7ed',
        'accent' => '#f59e0b',
        'secondary' => '#dc2626',
        'panel' => '#2a1609'
    ],
    'midnight_silver' => [
        'label' => 'Midnight Silver',
        'background' => '#05070b',
        'foreground' => '#f8fafc',
        'accent' => '#cbd5e1',
        'secondary' => '#64748b',
        'panel' => '#111827'
    ]
];

$fields = [
    'app_name' => 'My Yielded Vessels',
    'app_short_name' => 'MYV',
    'app_version' => '1.4',
    'ministry_name' => 'Your Ministry Name',
    'platform_domain' => 'https://iamyielded.org',
    'platform_path' => '/men_v14/',
    'login_logo_path' => '/men_v14/images/iamyielded.jpg',
    'app_icon_path' => '/men_v14/images/iamyieldedvov.jpg',
    'banner_image_path' => '',
    'theme_pack' => 'royal_dark',
    'theme_background' => '#0b1220',
    'theme_foreground' => '#eef4ff',
    'theme_color' => '#d4af37',
    'theme_accent' => '#6a0dad',
    'theme_panel' => '#121c2e',
    'menu_home' => 'Home',
    'menu_directory' => 'Directory',
    'menu_rotation' => 'Prayer Rotation',
    'menu_prayer' => 'Prayer Guide',
    'menu_assignments' => 'Assignments',
    'menu_admin' => 'Admin',
    'menu_logout' => 'Logout',
    'admin_heading' => 'Admin Area',
    'admin_intro' => 'Manage content without editing code.',
    'admin_label_settings' => 'Platform Settings Center',
    'admin_label_assignments' => 'Manage Assignments',
    'admin_label_prayer' => 'Manage Prayer Guide',
    'admin_label_directory' => 'Manage Directory',
    'admin_label_rotation' => 'Manage Prayer Rotation',
    'admin_label_users' => 'Registered Members',
    'admin_card_settings_title' => 'Platform Settings Center',
    'admin_card_settings_text' => 'Setup wizard, branding, colors, labels, and domain.',
    'dashboard_heading' => 'Welcome',
    'dashboard_subtitle' => 'This is your private ministry community platform.',
    'footer_text' => '© Your Ministry. All rights reserved. Private Use Only.'
];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS app_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(120) NOT NULL UNIQUE,
            setting_value TEXT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {
    try {
        $values = [];

        foreach ($fields as $key => $default) {
            $values[$key] = trim((string)($_POST[$key] ?? $default));
        }

        $pack = $values['theme_pack'] ?: 'royal_dark';
        if (!isset($themes[$pack])) {
            $pack = 'royal_dark';
        }

        if (!empty($_POST['use_theme_pack'])) {
            $values['theme_pack'] = $pack;
            $values['theme_background'] = $themes[$pack]['background'];
            $values['theme_foreground'] = $themes[$pack]['foreground'];
            $values['theme_color'] = $themes[$pack]['accent'];
            $values['theme_accent'] = $themes[$pack]['secondary'];
            $values['theme_panel'] = $themes[$pack]['panel'];
        }

        $values['login_logo_path'] = ps_upload_branding('login_logo_upload', $values['login_logo_path']);
        $values['app_icon_path'] = ps_upload_branding('app_icon_upload', $values['app_icon_path']);
        $values['banner_image_path'] = ps_upload_branding('banner_image_upload', $values['banner_image_path']);

        foreach ($values as $key => $value) {
            save_app_setting($pdo, $key, $value);
        }

        $notice = 'Platform settings saved.';
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$values = [];
foreach ($fields as $key => $default) {
    $values[$key] = app_setting($pdo, $key, $default);
}

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

<style>
.platform-theme-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(155px, 1fr));
    gap: 1rem;
}
.platform-theme-card {
    border: 1px solid rgba(255,255,255,.18);
    border-radius: 16px;
    padding: 1rem;
    background: rgba(255,255,255,.05);
    cursor: pointer;
}
.platform-theme-card input {
    width: auto;
    margin-right: .4rem;
}
.platform-theme-swatch {
    display: flex;
    height: 42px;
    overflow: hidden;
    border-radius: 12px;
    margin-top: .75rem;
    border: 1px solid rgba(255,255,255,.18);
}
.platform-theme-swatch span {
    flex: 1;
}
.platform-preview-menu {
    display:flex;
    flex-wrap:wrap;
    gap:.5rem;
    margin:.75rem 0;
}
.platform-preview-menu span {
    padding:.45rem .7rem;
    border-radius:10px;
    background:rgba(255,255,255,.08);
    border:1px solid rgba(255,255,255,.14);
}
</style>

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

<h1><?php echo h(app_setting($pdo, 'admin_label_settings', 'Platform Settings Center')); ?></h1>
<p class="muted">Protected back office setup wizard for identity, branding, colors, menus, admin labels, domain, and footer.</p>

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

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

<form method="post" enctype="multipart/form-data">

<div class="panel">
<h2>Identity</h2>
<div class="admin-grid">
<div><label>App Name</label><input name="app_name" value="<?php echo h($values['app_name']); ?>"></div>
<div><label>Short App Name</label><input name="app_short_name" value="<?php echo h($values['app_short_name']); ?>"></div>
<div><label>Version</label><input name="app_version" value="<?php echo h($values['app_version']); ?>"></div>
<div><label>Ministry Name</label><input name="ministry_name" value="<?php echo h($values['ministry_name']); ?>"></div>
</div>
</div>

<div class="panel">
<h2>Domain / Install Path</h2>
<div class="admin-grid">
<div><label>Platform Domain</label><input name="platform_domain" value="<?php echo h($values['platform_domain']); ?>"></div>
<div><label>Platform Path</label><input name="platform_path" value="<?php echo h($values['platform_path']); ?>"></div>
</div>
</div>

<div class="panel">
<h2>Visual Theme Picker</h2>
<p class="muted">Choose a theme by name. The colors below show the background, panel, accent, and secondary color.</p>

<div class="platform-theme-grid">
<?php foreach ($themes as $key => $theme): ?>
<label class="platform-theme-card">
<input type="radio" name="theme_pack" value="<?php echo h($key); ?>" <?php echo ($values['theme_pack'] === $key) ? 'checked' : ''; ?>>
<strong><?php echo h($theme['label']); ?></strong>
<div class="platform-theme-swatch">
<span style="background:<?php echo h($theme['background']); ?>"></span>
<span style="background:<?php echo h($theme['panel']); ?>"></span>
<span style="background:<?php echo h($theme['accent']); ?>"></span>
<span style="background:<?php echo h($theme['secondary']); ?>"></span>
</div>
</label>
<?php endforeach; ?>
</div>

<label style="margin-top:1rem;">
<input type="checkbox" name="use_theme_pack" checked style="width:auto;">
Use selected theme colors
</label>
</div>

<div class="panel">
<h2>Advanced Color Values</h2>
<div class="admin-grid">
<div><label>Background</label><input name="theme_background" value="<?php echo h($values['theme_background']); ?>"></div>
<div><label>Foreground/Text</label><input name="theme_foreground" value="<?php echo h($values['theme_foreground']); ?>"></div>
<div><label>Main Accent</label><input name="theme_color" value="<?php echo h($values['theme_color']); ?>"></div>
<div><label>Secondary Accent</label><input name="theme_accent" value="<?php echo h($values['theme_accent']); ?>"></div>
<div><label>Panel/Card Color</label><input name="theme_panel" value="<?php echo h($values['theme_panel']); ?>"></div>
</div>
</div>

<div class="panel">
<h2>Branding Images</h2>
<div class="admin-grid">
<div>
<label>Upload Login Logo</label>
<input type="file" name="login_logo_upload" accept="image/*">
<label>Login Logo Path / URL</label>
<input name="login_logo_path" value="<?php echo h($values['login_logo_path']); ?>">
</div>
<div>
<label>Upload App Icon / Splash Logo</label>
<input type="file" name="app_icon_upload" accept="image/*">
<label>App Icon / Splash Path / URL</label>
<input name="app_icon_path" value="<?php echo h($values['app_icon_path']); ?>">
</div>
<div>
<label>Upload Banner Image</label>
<input type="file" name="banner_image_upload" accept="image/*">
<label>Banner Image Path / URL</label>
<input name="banner_image_path" value="<?php echo h($values['banner_image_path']); ?>">
</div>
</div>
</div>

<div class="panel">
<h2>Menu Labels</h2>
<div class="admin-grid">
<div><label>Home</label><input name="menu_home" value="<?php echo h($values['menu_home']); ?>"></div>
<div><label>Directory</label><input name="menu_directory" value="<?php echo h($values['menu_directory']); ?>"></div>
<div><label>Prayer Rotation</label><input name="menu_rotation" value="<?php echo h($values['menu_rotation']); ?>"></div>
<div><label>Prayer Guide</label><input name="menu_prayer" value="<?php echo h($values['menu_prayer']); ?>"></div>
<div><label>Assignments / Courses</label><input name="menu_assignments" value="<?php echo h($values['menu_assignments']); ?>"></div>
<div><label>Admin</label><input name="menu_admin" value="<?php echo h($values['menu_admin']); ?>"></div>
<div><label>Logout</label><input name="menu_logout" value="<?php echo h($values['menu_logout']); ?>"></div>
</div>
</div>

<div class="panel">
<h2>Admin / Back Office Labels</h2>
<div class="admin-grid">
<div><label>Admin Heading</label><input name="admin_heading" value="<?php echo h($values['admin_heading']); ?>"></div>
<div><label>Admin Intro</label><input name="admin_intro" value="<?php echo h($values['admin_intro']); ?>"></div>
<div><label>Platform Settings</label><input name="admin_label_settings" value="<?php echo h($values['admin_label_settings']); ?>"></div>
<div><label>Assignments Admin</label><input name="admin_label_assignments" value="<?php echo h($values['admin_label_assignments']); ?>"></div>
<div><label>Prayer Guide Admin</label><input name="admin_label_prayer" value="<?php echo h($values['admin_label_prayer']); ?>"></div>
<div><label>Directory Admin</label><input name="admin_label_directory" value="<?php echo h($values['admin_label_directory']); ?>"></div>
<div><label>Rotation Admin</label><input name="admin_label_rotation" value="<?php echo h($values['admin_label_rotation']); ?>"></div>
<div><label>Registered Members</label><input name="admin_label_users" value="<?php echo h($values['admin_label_users']); ?>"></div>
</div>
</div>

<div class="panel">
<h2>Home / Footer Text</h2>
<label>Dashboard Heading</label>
<input name="dashboard_heading" value="<?php echo h($values['dashboard_heading']); ?>">

<label>Dashboard Subtitle</label>
<textarea name="dashboard_subtitle"><?php echo h($values['dashboard_subtitle']); ?></textarea>

<label>Footer Text</label>
<textarea name="footer_text"><?php echo h($values['footer_text']); ?></textarea>
</div>

<div class="panel">
<button class="btn btn-primary" type="submit">Save Platform Settings</button>
</div>
</form>

<div class="panel">
<h2>Live Preview</h2>
<h1><?php echo h($values['app_name']); ?></h1>
<p class="muted"><?php echo h($values['ministry_name']); ?> — Version <?php echo h($values['app_version']); ?></p>
<div class="platform-preview-menu">
<span><?php echo h($values['menu_home']); ?></span>
<span><?php echo h($values['menu_directory']); ?></span>
<span><?php echo h($values['menu_rotation']); ?></span>
<span><?php echo h($values['menu_prayer']); ?></span>
<span><?php echo h($values['menu_assignments']); ?></span>
<span><?php echo h($values['menu_admin']); ?></span>
</div>
<p><?php echo h($values['dashboard_subtitle']); ?></p>
<p class="muted"><?php echo h($values['footer_text']); ?></p>
</div>

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

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