<?php
declare(strict_types=1);
error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/config.php';

function sw_h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function sw_save(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 sw_get(PDO $pdo, string $key, string $default = ''): string {
    $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) ? (string)$value : $default;
}

function sw_upload_branding_file(string $fieldName, string $defaultPath): string {
    if (empty($_FILES[$fieldName]['name']) || empty($_FILES[$fieldName]['tmp_name'])) {
        return $defaultPath;
    }

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

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

    $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[$fieldName]['tmp_name'], $target)) {
        return 'uploads/branding/' . $filename;
    }

    return $defaultPath;
}

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

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

$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'
    ]
];

$defaults = [
    'app_name' => 'My Yielded Vessels',
    'ministry_name' => 'Your Ministry Name',
    'app_version' => '1.4 Concept',
    'theme_pack' => 'royal_dark',
    'theme_background' => '#0b1220',
    'theme_foreground' => '#eef4ff',
    'theme_color' => '#d4af37',
    'theme_accent' => '#6a0dad',
    'theme_panel' => '#121c2e',
    'login_logo_path' => '/men/images/iamyielded.jpg',
    'app_icon_path' => '/men/images/iamyieldedvov.jpg',
    'banner_image_path' => '',
    'menu_home' => 'Home',
    'menu_directory' => 'Directory',
    'menu_rotation' => 'Prayer Rotation',
    'menu_prayer' => 'Prayer Guide',
    'menu_assignments' => 'Assignments',
    'menu_admin' => 'Admin',
    'admin_label_dashboard' => 'Admin Dashboard',
    'admin_label_settings' => 'Platform Settings',
    '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',
    'dashboard_heading' => 'Welcome',
    'dashboard_subtitle' => 'This is your private ministry community platform.',
    'footer_text' => '© Your Ministry. All rights reserved. Private Use Only.'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {
    try {
        $themePack = (string)($_POST['theme_pack'] ?? 'royal_dark');
        if (!isset($themes[$themePack])) {
            $themePack = 'royal_dark';
        }

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

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

        $valuesToSave['login_logo_path'] = sw_upload_branding_file('login_logo_upload', $valuesToSave['login_logo_path']);
        $valuesToSave['app_icon_path'] = sw_upload_branding_file('app_icon_upload', $valuesToSave['app_icon_path']);
        $valuesToSave['banner_image_path'] = sw_upload_branding_file('banner_image_upload', $valuesToSave['banner_image_path']);

        foreach ($valuesToSave as $key => $value) {
            sw_save($pdo, $key, $value);
        }

        $notice = 'Setup settings saved. Theme and branding values are stored in app_settings.';
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

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

$currentTheme = $values['theme_pack'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Setup Wizard Concept</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root{
--bg:<?php echo sw_h($values['theme_background']); ?>;
--fg:<?php echo sw_h($values['theme_foreground']); ?>;
--accent:<?php echo sw_h($values['theme_color']); ?>;
--purple:<?php echo sw_h($values['theme_accent']); ?>;
--panel:<?php echo sw_h($values['theme_panel']); ?>;
}
*{box-sizing:border-box}
body{margin:0;font-family:Arial;background:var(--bg);color:var(--fg)}
.container{width:min(1100px,calc(100% - 2rem));margin:0 auto;padding:2rem 0}
.panel{background:linear-gradient(180deg,rgba(255,255,255,.08),rgba(255,255,255,.025));border:1px solid rgba(255,255,255,.15);border-radius:22px;padding:1.25rem;margin-bottom:1rem}
h1{font-size:clamp(2rem,5vw,3rem);margin:.2rem 0 1rem}
.grid{display:grid;grid-template-columns:repeat(2,1fr);gap:1rem}
.theme-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:.75rem}
.theme-card{border:1px solid rgba(255,255,255,.2);border-radius:14px;padding:.8rem;background:rgba(255,255,255,.06)}
.swatch{height:38px;border-radius:10px;margin:.4rem 0;display:flex;overflow:hidden}
.swatch span{flex:1}
label{display:block;font-weight:bold;margin:.6rem 0 .25rem}
input,textarea,select{width:100%;padding:.85rem;border-radius:12px;border:1px solid rgba(255,255,255,.15);background:rgba(255,255,255,.08);color:var(--fg)}
textarea{min-height:90px}
button,.btn{display:inline-flex;padding:.85rem 1rem;border-radius:13px;border:0;font-weight:bold;cursor:pointer;background:linear-gradient(135deg,var(--purple),var(--accent));color:white;text-decoration:none;margin-top:1rem}
.notice{padding:1rem;border-radius:14px;background:rgba(31,157,85,.15);border:1px solid rgba(31,157,85,.3);margin-bottom:1rem}
.error{padding:1rem;border-radius:14px;background:rgba(226,91,82,.15);border:1px solid rgba(226,91,82,.3);margin-bottom:1rem}
.preview-menu{display:flex;gap:.45rem;flex-wrap:wrap}
.preview-menu span{padding:.5rem .7rem;border-radius:10px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.15);font-size:.9rem;font-weight:bold}
.muted{color:rgba(238,244,255,.75)}
.logo-preview{max-height:90px;max-width:220px;border-radius:12px;border:1px solid rgba(255,255,255,.15);background:#fff;padding:.35rem}
@media(max-width:900px){.grid,.theme-grid{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="container">
<div class="panel">
<h1>Ministry Platform Setup Wizard</h1>
<p class="muted">Step 1B concept. Upload logos, choose a theme, or enter custom image paths and colors.</p>
</div>

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

<form method="post" enctype="multipart/form-data">
<div class="panel"><h2>1. Identity</h2><div class="grid">
<div><label>App Name</label><input name="app_name" value="<?php echo sw_h($values['app_name']); ?>"></div>
<div><label>Ministry Name</label><input name="ministry_name" value="<?php echo sw_h($values['ministry_name']); ?>"></div>
<div><label>Version</label><input name="app_version" value="<?php echo sw_h($values['app_version']); ?>"></div>
</div></div>

<div class="panel"><h2>2. Simple Theme Picker</h2>
<p class="muted">Choose a theme pack, then check “Use Theme Pack Colors” before saving.</p>
<div class="theme-grid">
<?php foreach ($themes as $key => $theme): ?>
<label class="theme-card">
<input type="radio" name="theme_pack" value="<?php echo sw_h($key); ?>" <?php echo $currentTheme === $key ? 'checked' : ''; ?> style="width:auto;">
<?php echo sw_h($theme['label']); ?>
<div class="swatch">
<span style="background:<?php echo sw_h($theme['background']); ?>"></span>
<span style="background:<?php echo sw_h($theme['panel']); ?>"></span>
<span style="background:<?php echo sw_h($theme['accent']); ?>"></span>
<span style="background:<?php echo sw_h($theme['secondary']); ?>"></span>
</div>
</label>
<?php endforeach; ?>
</div>
<label><input type="checkbox" name="use_theme_pack" checked style="width:auto;"> Use Theme Pack Colors</label>
</div>

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

<div class="panel"><h2>4. Branding Images</h2>
<p class="muted">Use upload buttons for simplicity or paste a URL/path for advanced use.</p>
<div class="grid">
<div>
<label>Upload Login Logo</label>
<input type="file" name="login_logo_upload" accept="image/*">
<label>Login Logo Path or URL</label>
<input name="login_logo_path" value="<?php echo sw_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 or URL</label>
<input name="app_icon_path" value="<?php echo sw_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 or URL</label>
<input name="banner_image_path" value="<?php echo sw_h($values['banner_image_path']); ?>">
</div>
</div>
</div>

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


<div class="panel"><h2>6. Admin / Back Office Labels</h2>
<p class="muted">These names control the Admin area cards and back office module titles.</p>
<div class="grid">
<div><label>Admin Dashboard Title</label><input name="admin_label_dashboard" value="<?php echo sw_h($values['admin_label_dashboard']); ?>"></div>
<div><label>Platform Settings</label><input name="admin_label_settings" value="<?php echo sw_h($values['admin_label_settings']); ?>"></div>
<div><label>Assignments Admin</label><input name="admin_label_assignments" value="<?php echo sw_h($values['admin_label_assignments']); ?>"></div>
<div><label>Prayer Guide Admin</label><input name="admin_label_prayer" value="<?php echo sw_h($values['admin_label_prayer']); ?>"></div>
<div><label>Directory Admin</label><input name="admin_label_directory" value="<?php echo sw_h($values['admin_label_directory']); ?>"></div>
<div><label>Rotation Admin</label><input name="admin_label_rotation" value="<?php echo sw_h($values['admin_label_rotation']); ?>"></div>
<div><label>Registered Members</label><input name="admin_label_users" value="<?php echo sw_h($values['admin_label_users']); ?>"></div>
</div></div>

<div class="panel"><h2>7. Home Screen Text</h2>
<label>Dashboard Heading</label><input name="dashboard_heading" value="<?php echo sw_h($values['dashboard_heading']); ?>">
<label>Dashboard Subtitle</label><textarea name="dashboard_subtitle"><?php echo sw_h($values['dashboard_subtitle']); ?></textarea>
<label>Footer Text</label><textarea name="footer_text"><?php echo sw_h($values['footer_text']); ?></textarea>
</div>

<div class="panel"><button type="submit">Run Setup / Save Settings</button></div>
</form>

<div class="panel">
<h2>Live Concept Preview</h2>
<?php if ($values['login_logo_path']): ?><img class="logo-preview" src="<?php echo sw_h($values['login_logo_path']); ?>" alt="Login Logo"><?php endif; ?>
<h1><?php echo sw_h($values['app_name']); ?></h1>
<p class="muted"><?php echo sw_h($values['ministry_name']); ?> — Version <?php echo sw_h($values['app_version']); ?></p>
<div class="preview-menu">
<span><?php echo sw_h($values['menu_home']); ?></span>
<span><?php echo sw_h($values['menu_directory']); ?></span>
<span><?php echo sw_h($values['menu_rotation']); ?></span>
<span><?php echo sw_h($values['menu_prayer']); ?></span>
<span><?php echo sw_h($values['menu_assignments']); ?></span>
<span><?php echo sw_h($values['menu_admin']); ?></span>
</div>

<h2>Admin / Back Office Preview</h2>
<div class="preview-menu">
<span><?php echo sw_h($values['admin_label_dashboard']); ?></span>
<span><?php echo sw_h($values['admin_label_settings']); ?></span>
<span><?php echo sw_h($values['admin_label_assignments']); ?></span>
<span><?php echo sw_h($values['admin_label_prayer']); ?></span>
<span><?php echo sw_h($values['admin_label_directory']); ?></span>
<span><?php echo sw_h($values['admin_label_rotation']); ?></span>
<span><?php echo sw_h($values['admin_label_users']); ?></span>
</div>

<h2><?php echo sw_h($values['dashboard_heading']); ?></h2>
<p><?php echo sw_h($values['dashboard_subtitle']); ?></p>
<p class="muted"><?php echo sw_h($values['footer_text']); ?></p>
</div>
</div>
</body>
</html>
