<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;

class WhmcsAuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        $response = Http::asForm()->post(config('whmcs.url'), [
            'action' => 'ValidateLogin',
            'username' => config('whmcs.identifier'),
            'password' => config('whmcs.secret'),
            'email' => $request->email,
            'password2' => $request->password,
            'responsetype' => 'json',
        ]);

        $data = $response->json();

        if(isset($data['result']) && $data['result'] === 'success') {
            // موفق → ایجاد session لاراول
            $user = [
                'userid' => $data['userid'],
                'email' => $request->email,
                'firstname' => $data['firstname'] ?? '',
                'lastname' => $data['lastname'] ?? '',
            ];

            session(['whmcs_user' => $user]);

            return redirect()->route('dashboard');
        }

        return back()->withErrors(['email' => 'اطلاعات ورود اشتباه است']);
    }

    public function logout()
    {
        session()->forget('whmcs_user');
        return redirect()->route('login');
    }
}
