<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use App\Models\Customer;

class SsoController extends Controller
{
    public function login(Request $req)
    {
        // 1) รับ token
        $p = $req->query('p');  // payload (base64 json)
        $s = $req->query('s');  // signature (hmac)
        if (!$p || !$s) abort(401, 'Missing token');

        // 2) ตรวจลายเซ็น
        $secret = config('app.sso_secret_saslog');
        $calc   = hash_hmac('sha256', $p, $secret);
        if (!hash_equals($calc, $s)) abort(401, 'Bad signature');

        // 3) ถอด payload + ตรวจอายุ + กันรีเพลย์
        $data = json_decode(base64_decode($p), true);
        if (!$data || !is_array($data)) abort(401, 'Bad payload');

        $exp = (int)($data['exp'] ?? 0);
        if (time() > $exp) abort(401, 'Token expired');

        $jti = $data['jti'] ?? null;
        if (!$jti || Cache::has('sso:jti:'.$jti)) abort(401, 'Token already used');
        Cache::put('sso:jti:'.$jti, 1, now()->addMinutes(2));

        // 4) ผูกปลายทาง
        $expectedHost = parse_url(config('app.url'), PHP_URL_HOST);
        if (($data['host'] ?? '') !== $expectedHost) abort(401, 'Wrong host');
        if (($data['aud']  ?? '') !== 'saslog')       abort(401, 'Wrong audience');

        // 5) ดึงข้อมูลจำเป็นจาก payload
        $email    = strtolower(trim($data['email'] ?? ''));
        $agencyId = (int)($data['agency_id'] ?? 0);
        $levelInToken = (string)($data['level'] ?? '');   // ไม่แก้เคส

        if ($email === '')   abort(401, 'Email required');
        if ($agencyId <= 0)  abort(401, 'Agency_ID required');

        // 6) หา user แล้วล็อกอิน
        $user = Customer::where('Email', $email)->orWhere('email', $email)->first();
        if (!$user) abort(401, 'User not found');

        Auth::login($user, true);
        $req->session()->regenerate();

        // 7) หา Agency
        $agencyRow = null; $agencyName = null;
        if (Schema::hasTable('agency')) {
            $agencyRow  = DB::table('agency')->where('Agency_ID', $agencyId)->first();
            $agencyName = $agencyRow->Agency_Name ?? null;
        } elseif (Schema::hasTable('agencies')) {
            $agencyRow  = DB::table('agencies')->where('id', $agencyId)->first();
            $agencyName = $agencyRow->name ?? null;
        }
        if (!$agencyRow) {
            Log::warning('[SSO] Agency not found', ['agency_id' => $agencyId, 'email' => $email]);
            abort(401, 'Agency not found');
        }

        // 8) เซ็ต session กลาง
        session([
            'current_agency_id'   => (int)$agencyId,
            'current_agency_name' => (string)($agencyName ?? '—'),
            'current_level'       => ($user->Level ?? $levelInToken),
        ]);

        // 9) persist Agency_ID ให้ user ถ้ามีคอลัมน์
        if (Schema::hasColumn('customer', 'Agency_ID')) {
            try {
                if ((int)($user->Agency_ID ?? 0) !== $agencyId) {
                    $user->Agency_ID = $agencyId;
                    $user->save();
                }
            } catch (\Throwable $e) {
                Log::warning('[SSO] cannot persist user Agency_ID', ['err' => $e->getMessage()]);
            }
        }

        // 10) เลือกปลายทางตาม Level
        $level = (string)($user->Level ?? $levelInToken);
        $eq = fn($a,$b) => strcasecmp((string)$a, (string)$b) === 0;

        if ($eq($level, 'SuperAdmin') || $eq($level, 'Admin')) {
            $target = route_exists('admin.dashboard') ? route('admin.dashboard') : '/admin/dashboard';
        } elseif ($eq($level, 'Consultant')) {
            $target = route_exists('consultant.dashboard') ? route('consultant.dashboard') : '/consultant/dashboard';
        } else {
            $target = route_exists('user.dashboard') ? route('user.dashboard') : '/dashboard';
        }

        return redirect()->intended($target);
    }
}

/** เช็คว่ามี route ชื่อนี้ไหม */
if (! function_exists('route_exists')) {
    function route_exists(string $name): bool {
        try { return \Illuminate\Support\Facades\Route::has($name); }
        catch (\Throwable $e) { return false; }
    }
}
