<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if (!function_exists('nay_home_db')) {
    function nay_home_db(): ?mysqli
    {
        global $conn;
        return $conn instanceof mysqli ? $conn : null;
    }
}

if (!function_exists('nay_home_h')) {
    function nay_home_h(?string $value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('nay_home_setting')) {
    function nay_home_setting(?mysqli $conn, string $key, string $default = ''): string
    {
        if (!$conn instanceof mysqli) {
            return $default;
        }
        $stmt = $conn->prepare('SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1');
        if (!$stmt) {
            return $default;
        }
        $stmt->bind_param('s', $key);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        return $row && array_key_exists('setting_value', $row) ? (string)$row['setting_value'] : $default;
    }
}

if (!function_exists('nay_home_enabled')) {
    function nay_home_enabled(?mysqli $conn, string $key, bool $default = true): bool
    {
        $value = strtolower(trim(nay_home_setting($conn, $key, $default ? '1' : '0')));
        return in_array($value, ['1', 'true', 'yes', 'on'], true);
    }
}

if (!function_exists('nay_home_upsert')) {
    function nay_home_upsert(?mysqli $conn, string $key, string $value, string $group = 'home'): void
    {
        if (!$conn instanceof mysqli || $key === '') {
            return;
        }
        $stmt = $conn->prepare('INSERT INTO settings (setting_key, setting_value, setting_group, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW()) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), setting_group = VALUES(setting_group), updated_at = NOW()');
        if ($stmt) {
            $stmt->bind_param('sss', $key, $value, $group);
            $stmt->execute();
            $stmt->close();
        }
    }
}

if (!function_exists('nay_home_color')) {
    function nay_home_color(string $value, string $fallback): string
    {
        $value = trim($value);
        if ($value === '') {
            return $fallback;
        }
        if ($value[0] !== '#') {
            $value = '#' . $value;
        }
        return preg_match('/^#[0-9a-fA-F]{6}$/', $value) ? strtoupper($value) : $fallback;
    }
}

if (!function_exists('nay_home_upload_image')) {
    function nay_home_upload_image(string $field): string
    {
        if (empty($_FILES[$field]) || !is_array($_FILES[$field]) || (int)($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
            return '';
        }
        $file = $_FILES[$field];
        if ((int)($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
            return '';
        }
        $tmp = (string)($file['tmp_name'] ?? '');
        $name = (string)($file['name'] ?? '');
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true) || !is_uploaded_file($tmp)) {
            return '';
        }
        $dir = dirname(__DIR__) . '/uploads/home';
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }
        $safeName = 'home_hero_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $target = $dir . '/' . $safeName;
        if (!move_uploaded_file($tmp, $target)) {
            return '';
        }
        return 'home/' . $safeName;
    }
}

if (!function_exists('nay_home_defaults')) {
    function nay_home_defaults(): array
    {
        return [
            'home_hero_enabled' => '1',
            'home_show_quick_actions' => '1',
            'home_show_search_bar' => '1',
            'home_hero_pill_text' => '',
            'home_hero_title' => '',
            'home_hero_subtitle' => '',
            'home_hero_image_url' => '',
            'home_hero_image_opacity' => '0.28',
            'home_hero_background_color' => '#EAF8FD',
            'home_hero_gradient_color' => '#FFE7EF',
            'home_hero_text_color' => '#263744',
            'home_hero_subtitle_color' => '#7C92A0',
            'home_hero_pill_background_color' => '#FFFFFF',
            'home_hero_pill_text_color' => '#17495A',
            'home_hero_link_type' => 'none',
            'home_hero_link_value' => '',
            'home_soft_banner_enabled' => '0',
            'home_soft_banner_title' => '',
            'home_soft_banner_subtitle' => '',
            'home_soft_banner_icon' => 'spa',
            'home_soft_banner_image_url' => '',
            'home_soft_banner_background_color' => '#DDECF6',
            'home_soft_banner_link_type' => 'none',
            'home_soft_banner_link_value' => '',
            'home_soft_banner_sort_order' => '40',
            'home_feature_1_enabled' => '1',
            'home_feature_1_label' => '',
            'home_feature_1_icon' => 'local_shipping',
            'home_feature_2_enabled' => '1',
            'home_feature_2_label' => '',
            'home_feature_2_icon' => 'redeem',
            'home_feature_3_enabled' => '1',
            'home_feature_3_label' => '',
            'home_feature_3_icon' => 'stars',
            'home_feature_4_enabled' => '1',
            'home_feature_4_label' => '',
            'home_feature_4_icon' => 'payments',
        ];
    }
}

if (!function_exists('nay_home_ensure_defaults')) {
    function nay_home_ensure_defaults(?mysqli $conn): void
    {
        foreach (nay_home_defaults() as $key => $value) {
            if (nay_home_setting($conn, $key, '__missing__') === '__missing__') {
                nay_home_upsert($conn, $key, $value, 'home');
            }
        }
    }
}

if (!function_exists('nay_home_values')) {
    function nay_home_values(?mysqli $conn): array
    {
        $values = [];
        foreach (nay_home_defaults() as $key => $default) {
            $values[$key] = nay_home_setting($conn, $key, $default);
        }
        return $values;
    }
}

if (!function_exists('nay_home_save')) {
    function nay_home_save(?mysqli $conn, array $post): array
    {
        if (!$conn instanceof mysqli) {
            return ['ok' => false, 'message' => 'تعذر الاتصال بقاعدة البيانات.'];
        }

        $checkboxes = [
            'home_hero_enabled',
            'home_show_quick_actions',
            'home_show_search_bar',
            'home_soft_banner_enabled',
            'home_feature_1_enabled',
            'home_feature_2_enabled',
            'home_feature_3_enabled',
            'home_feature_4_enabled',
        ];
        foreach ($checkboxes as $key) {
            nay_home_upsert($conn, $key, isset($post[$key]) ? '1' : '0', 'home');
        }

        $textKeys = [
            'home_hero_pill_text',
            'home_hero_title',
            'home_hero_subtitle',
            'home_hero_image_url',
            'home_hero_link_value',
            'home_soft_banner_title',
            'home_soft_banner_subtitle',
            'home_soft_banner_icon',
            'home_soft_banner_image_url',
            'home_soft_banner_link_value',
            'home_soft_banner_sort_order',
            'home_feature_1_label',
            'home_feature_1_icon',
            'home_feature_2_label',
            'home_feature_2_icon',
            'home_feature_3_label',
            'home_feature_3_icon',
            'home_feature_4_label',
            'home_feature_4_icon',
        ];
        foreach ($textKeys as $key) {
            nay_home_upsert($conn, $key, trim((string)($post[$key] ?? '')), 'home');
        }

        $linkType = trim((string)($post['home_hero_link_type'] ?? 'none'));
        if (!in_array($linkType, ['none', 'category', 'brand', 'product', 'external'], true)) {
            $linkType = 'none';
        }
        nay_home_upsert($conn, 'home_hero_link_type', $linkType, 'home');

        $softLinkType = trim((string)($post['home_soft_banner_link_type'] ?? 'none'));
        if (!in_array($softLinkType, ['none', 'category', 'brand', 'product', 'offers', 'favorites', 'notifications', 'search', 'url', 'external'], true)) {
            $softLinkType = 'none';
        }
        nay_home_upsert($conn, 'home_soft_banner_link_type', $softLinkType, 'home');

        $opacity = (float)($post['home_hero_image_opacity'] ?? 0.28);
        $opacity = max(0, min(1, $opacity));
        nay_home_upsert($conn, 'home_hero_image_opacity', (string)$opacity, 'home');

        foreach ([
            'home_hero_background_color' => '#EAF8FD',
            'home_hero_gradient_color' => '#FFE7EF',
            'home_hero_text_color' => '#263744',
            'home_hero_subtitle_color' => '#7C92A0',
            'home_hero_pill_background_color' => '#FFFFFF',
            'home_hero_pill_text_color' => '#17495A',
            'home_soft_banner_background_color' => '#DDECF6',
        ] as $key => $fallback) {
            nay_home_upsert($conn, $key, nay_home_color((string)($post[$key] ?? ''), $fallback), 'home');
        }

        $uploaded = nay_home_upload_image('home_hero_image_file');
        if ($uploaded !== '') {
            nay_home_upsert($conn, 'home_hero_image_url', $uploaded, 'home');
        }
        $softUploaded = nay_home_upload_image('home_soft_banner_image_file');
        if ($softUploaded !== '') {
            nay_home_upsert($conn, 'home_soft_banner_image_url', $softUploaded, 'home');
        }

        if (function_exists('admin_log_activity')) {
            admin_log_activity('app_home.update', 'تحديث واجهة التطبيق', 'تم حفظ إعدادات واجهة التطبيق الرئيسية.', 'settings', 'home', [], true);
        }

        return ['ok' => true, 'message' => 'تم حفظ إعدادات بنرات التطبيق والميزات بنجاح.'];
    }
}
