<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RememberClient
{
    /**
     * "Beni hatırla" cookie'si ile otomatik oturum açma
     */
    public function handle(Request $request, Closure $next)
    {
        // Zaten login ise ya da cookie yoksa devam et
        if (Session::has('client') || !Cookie::has('remember_client')) {
            return $next($request);
        }

        $rememberToken = Cookie::get('remember_client');

        try {
            // Token kaydını çek
            $record = DB::table('sspanel_token')
                ->where('token', $rememberToken)
                ->first();

            if (!$record) {
                return $next($request);
            }

            // Kullanıcı + Client bilgisi (WHMCS şeması)
            // İsim/soyisim/telefon tblclients'ta tutulur.
            $user = DB::table('tblusers as u')
                ->leftJoin('tblusers_clients as uc', 'u.id', '=', 'uc.userid')
                ->leftJoin('tblclients as c', 'uc.client_id', '=', 'c.id')
                ->where('u.id', $record->user_id)
                ->select(
                    'u.id as user_id',
                    'c.id as client_id',
                    'c.firstname as first_name',
                    'c.lastname  as last_name',
                    'c.phonenumber'
                )
                ->first();

            if ($user) {
                // Güvenli atamalar
                Session::put('client',            $user->user_id);       // user_id
                Session::put('client_id',         $user->client_id ?? 0); // whmcs client id (varsa)
                Session::put('client_firstname',  $user->first_name ?? '');
                Session::put('client_lastname',   $user->last_name  ?? '');
                Session::put('client_phone',      $user->phonenumber ?? '');

                Log::info('Auto login via remember_client cookie', [
                    'user_id' => $user->user_id,
                    'client_id' => $user->client_id,
                    'ip'      => $request->ip(),
                    'ua'      => $request->userAgent(),
                ]);
            }
        } catch (\Throwable $e) {
            // Sessiz geç; uygulamayı düşürmeyelim
            Log::warning('RememberClient middleware error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
        }

        return $next($request);
    }
}
