<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MobileAppController extends Controller
{
    public function index()
    {
        // App settings
        $settings = [
            'mobile_min_version'        => Setting::get('mobile_min_version', '1.0.0'),
            'mobile_current_version'    => Setting::get('mobile_current_version', '1.0.0'),
            'mobile_apk_url'            => Setting::get('mobile_apk_url', ''),
            'mobile_maintenance_mode'   => Setting::get('mobile_maintenance_mode', '0'),
            'mobile_maintenance_message'=> Setting::get('mobile_maintenance_message', 'Uygulama şu anda bakımda. Lütfen daha sonra tekrar deneyin.'),
            'mobile_force_update_msg'   => Setting::get('mobile_force_update_msg', 'Uygulamayı kullanmaya devam etmek için lütfen güncelleyin.'),
        ];

        // Stats
        $stats = [
            'total_users'       => User::count(),
            'fcm_tokens'        => User::whereNotNull('fcm_token')->where('fcm_token', '!=', '')->count(),
            'notifications_sent'=> UserNotification::count(),
            'notifs_today'      => UserNotification::whereDate('created_at', today())->count(),
            'notifs_unread'     => UserNotification::whereNull('read_at')->count(),
        ];

        // Active users (logged in last 30 days, via tokens)
        try {
            $stats['active_30d'] = DB::table('personal_access_tokens')
                ->where('tokenable_type', User::class)
                ->where('last_used_at', '>=', now()->subDays(30))
                ->distinct('tokenable_id')
                ->count('tokenable_id');
        } catch (\Throwable $e) {
            $stats['active_30d'] = '–';
        }

        return view('admin.mobile.index', compact('settings', 'stats'));
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'mobile_min_version'         => 'required|string|max:20',
            'mobile_current_version'     => 'required|string|max:20',
            'mobile_apk_url'             => 'nullable|url|max:500',
            'mobile_maintenance_mode'    => 'boolean',
            'mobile_maintenance_message' => 'required|string|max:300',
            'mobile_force_update_msg'    => 'required|string|max:300',
        ]);

        // Checkbox absent = unchecked → force '0'
        $data['mobile_maintenance_mode'] = $request->boolean('mobile_maintenance_mode') ? '1' : '0';

        foreach ($data as $key => $value) {
            Setting::set($key, $value ?? '', 'mobile');
        }

        return back()->with('success', 'Mobil uygulama ayarları güncellendi.');
    }
}
