<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SettingModel;

class AppVersion extends BaseController
{
    public function index()
    {
        $settings = model(SettingModel::class);
        $content = view('admin/app_version', [
            'app_min_version'        => $settings->getValue('app_min_version') ?? '',
            'app_store_url_google'   => $settings->getValue('app_store_url_google') ?? '',
            'app_store_url_apple'    => $settings->getValue('app_store_url_apple') ?? '',
            'app_store_url_huawei'   => $settings->getValue('app_store_url_huawei') ?? '',
            'app_direct_apk_url'     => $settings->getValue('app_direct_apk_url') ?? '',
        ]);
        return view('admin/layout', ['title' => 'App Version', 'content' => $content]);
    }

    public function save()
    {
        $settings = model(SettingModel::class);

        $minVersion = $this->request->getPost('app_min_version');
        if ($minVersion !== null) {
            $settings->setValue('app_min_version', trim((string) $minVersion));
        }

        $google = $this->request->getPost('app_store_url_google');
        if ($google !== null) {
            $settings->setValue('app_store_url_google', trim((string) $google));
        }

        $apple = $this->request->getPost('app_store_url_apple');
        if ($apple !== null) {
            $settings->setValue('app_store_url_apple', trim((string) $apple));
        }

        $huawei = $this->request->getPost('app_store_url_huawei');
        if ($huawei !== null) {
            $settings->setValue('app_store_url_huawei', trim((string) $huawei));
        }

        $directApk = $this->request->getPost('app_direct_apk_url');
        if ($directApk !== null) {
            $settings->setValue('app_direct_apk_url', trim((string) $directApk));
        }

        return redirect()->to(base_url('admin/app-version'))->with('message', 'App version settings saved.');
    }
}
