<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Database;
use App\Core\Response;

$pdo = Database::connection();
$input = request_input();
$method = $_SERVER['REQUEST_METHOD'];
$action = $input['action'] ?? 'public';

function pyrk_brand_footer_defaults(): array
{
    return [
        // Top navigation / header brand
        'header_logo_text' => 'PY',
        'header_logo_image_path' => '',
        'header_admin_brand_name' => 'Pyrk Admin',
        'header_client_brand_name' => 'Pyrk',
        'header_subtitle' => 'Walking Club',

        // Footer
        'footer_enabled' => '1',
        'footer_logo_text' => 'PY',
        'footer_brand_name' => 'Pyrk Walking Club',
        'footer_tagline' => 'Walk together. Grow stronger. Celebrate the journey.',
        'footer_description' => 'Pyrk Walking Club brings the community together through organized walks, safe routes, checkpoints, photo contests, loyalty points, and badges.',
        'footer_address' => 'Beirut, Lebanon',
        'footer_phone' => '',
        'footer_email' => '',
        'footer_whatsapp_url' => '',
        'footer_instagram_url' => '',
        'footer_facebook_url' => '',
        'footer_copyright' => '© {year} Pyrk Walking Club. All rights reserved.',
        'footer_show_quick_links' => '1',
        'footer_show_contact' => '1',
        'footer_show_social' => '1',
        'footer_accent_note' => 'Safety, community, wellness, and memories from every walk.',
    ];
}

function pyrk_settings_table(PDO $pdo): void
{
    $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 NOT NULL,
        updated_by INT NULL,
        created_at DATETIME NULL,
        updated_at DATETIME NULL,
        INDEX idx_app_settings_key (setting_key)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
}

function pyrk_load_brand_footer_settings(PDO $pdo): array
{
    $defaults = pyrk_brand_footer_defaults();
    try {
        pyrk_settings_table($pdo);
        $keys = array_keys($defaults);
        $placeholders = implode(',', array_fill(0, count($keys), '?'));
        $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ($placeholders)");
        $stmt->execute($keys);
        $settings = $defaults;
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if (array_key_exists($row['setting_key'], $settings)) {
                $settings[$row['setting_key']] = (string)$row['setting_value'];
            }
        }
        return $settings;
    } catch (Throwable $e) {
        return $defaults;
    }
}

function pyrk_clean_url(string $url): string
{
    $url = trim($url);
    if ($url === '') return '';
    return preg_match('~^https?://~i', $url) ? $url : '';
}

function pyrk_save_setting(PDO $pdo, string $key, string $value, int $adminId): void
{
    $stmt = $pdo->prepare('INSERT INTO app_settings (setting_key, setting_value, updated_by, created_at, updated_at)
        VALUES (?, ?, ?, NOW(), NOW())
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_by = VALUES(updated_by), updated_at = NOW()');
    $stmt->execute([$key, $value, $adminId]);
}

function pyrk_upload_header_logo(array $file): string
{
    if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
        return '';
    }

    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        Response::error('Logo upload failed. Please try another image.');
    }

    $maxBytes = 2 * 1024 * 1024;
    if (($file['size'] ?? 0) > $maxBytes) {
        Response::error('Logo image is too large. Maximum size is 2MB.');
    }

    $imageInfo = @getimagesize($file['tmp_name']);
    $mime = $imageInfo['mime'] ?? '';
    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    ];

    if (!isset($allowed[$mime])) {
        Response::error('Logo must be JPG, PNG, or WEBP. SVG is not allowed for security.');
    }

    $uploadDir = realpath(__DIR__ . '/../public');
    if (!$uploadDir) {
        Response::error('Public upload directory was not found.');
    }

    $targetDir = $uploadDir . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'site';
    if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true)) {
        Response::error('Could not create site logo upload folder.');
    }

    $filename = 'header_logo_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $allowed[$mime];
    $target = $targetDir . DIRECTORY_SEPARATOR . $filename;

    if (!move_uploaded_file($file['tmp_name'], $target)) {
        Response::error('Could not save the uploaded logo.');
    }

    return 'uploads/site/' . $filename;
}

if ($method === 'GET' && ($action === 'public' || $action === 'settings')) {
    if ($action === 'settings') {
        Auth::requireRole(['super_admin', 'event_manager']);
    }
    $settings = pyrk_load_brand_footer_settings($pdo);
    $settings['footer_enabled_bool'] = $settings['footer_enabled'] === '1';
    $settings['footer_show_quick_links_bool'] = $settings['footer_show_quick_links'] === '1';
    $settings['footer_show_contact_bool'] = $settings['footer_show_contact'] === '1';
    $settings['footer_show_social_bool'] = $settings['footer_show_social'] === '1';
    Response::ok(['settings' => $settings]);
}

if ($method === 'POST' && $action === 'save') {
    $admin = Auth::requireRole(['super_admin', 'event_manager']);
    Csrf::validateFromRequest();
    pyrk_settings_table($pdo);

    $defaults = pyrk_brand_footer_defaults();
    $current = pyrk_load_brand_footer_settings($pdo);
    $allowed = array_keys($defaults);
    $values = [];

    foreach ($allowed as $key) {
        if ($key === 'header_logo_image_path') {
            $values[$key] = $current[$key] ?? '';
            continue;
        }

        $value = $input[$key] ?? $defaults[$key];

        if (in_array($key, ['footer_enabled', 'footer_show_quick_links', 'footer_show_contact', 'footer_show_social'], true)) {
            $value = !empty($value) && $value !== '0' && $value !== 'false' ? '1' : '0';
        } elseif (str_ends_with($key, '_url')) {
            $value = pyrk_clean_url((string)$value);
        } else {
            $value = trim((string)$value);
            $max = in_array($key, ['footer_description'], true) ? 900 : 260;
            if (function_exists('mb_strlen') && mb_strlen($value) > $max) {
                $value = mb_substr($value, 0, $max);
            } elseif (strlen($value) > $max) {
                $value = substr($value, 0, $max);
            }
        }

        $values[$key] = $value;
    }

    if (!empty($input['header_remove_logo'])) {
        $values['header_logo_image_path'] = '';
    }

    if (!empty($_FILES['header_logo_image']['tmp_name'])) {
        $values['header_logo_image_path'] = pyrk_upload_header_logo($_FILES['header_logo_image']);
    }

    if ($values['header_logo_text'] === '') {
        $values['header_logo_text'] = 'PY';
    }
    if ($values['header_admin_brand_name'] === '') {
        Response::error('Admin brand name is required.');
    }
    if ($values['header_client_brand_name'] === '') {
        Response::error('Client brand name is required.');
    }
    if ($values['header_subtitle'] === '') {
        $values['header_subtitle'] = 'Walking Club';
    }
    if ($values['footer_brand_name'] === '') {
        Response::error('Footer brand name is required.');
    }

    foreach ($values as $key => $value) {
        pyrk_save_setting($pdo, $key, (string)$value, (int)$admin['id']);
    }

    Response::ok(['settings' => $values], 'Branding and footer saved.');
}

Response::error('Unsupported settings action.', 404);
