<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class AuthController extends Controller
{
    public function checkCustomer($customer = '')
    {
        if(empty($customer)) {
            $customer = session('customer') ?? '';
        }
        if($customer == '') return view('notvalid');
        session(['customer' => $customer], Carbon::now()->addYear());
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, env('API_URL')."check-customer/".$customer);
        curl_setopt($ch, CURLOPT_POST, true);
        $postData = json_encode([]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($postData)
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_errno($ch);
        curl_close($ch);

        if ($curlError || $httpCode >= 400) {
            return view('notvalid');
        }

        $responseData = json_decode($response, true);
        if (empty($responseData['data'])) {
            return view('notvalid');
        }
        session([$customer => $responseData['data']]);
        $isAuth = $responseData['data']['is_auth'] ?? [];
        $authlist = array_keys($isAuth, 'yes');
        if (count($authlist) === 0) {
            return view('404');
        } elseif (count($authlist) >= 2) {
            return redirect('/ehr/list');
        } else {
            $slugs = ['OYSTEHR' => 'ehr-default', 'EPIC' => 'epic', 'EKACARE' => 'eka-care'];
            return isset($slugs[$authlist[0]])
                ? redirect()->route('login', [$slugs[$authlist[0]]])
                : view('404');
        }
        return view('notvalid');
    }

    public function login($slug = '')
    {
        // Ensure customer is set
        if (!session()->has('customer')) {
            $this->checkCustomer();
        }
        // If nothing is authenticated and no slug provided, redirect to list
        if (
            !session()->has('authenticated') &&
            !session()->has('currentEHR') &&
            $slug === ''
        ) {
            return redirect('/ehr/list');
        }
        // If slug is missing but currentEHR exists in session, use it
        if ($slug === '' && session()->has('currentEHR') && session('currentEHR') !== '') {
            $slug = session('currentEHR');
        }
        // Store the EHR slug
        if ($slug !== '') {
            session(['currentEHR' => $slug]);
        }
        // Redirect to auth server
        $authUrl = env('AUTH_SERVER_URL') . "/$slug/login";
        $state = env('WEB_URL') . "/callback";
        $customer = session('customer');

        return redirect("{$authUrl}?state={$state}&customer={$customer}");
    }
    
    public function callback(Request $request)
    {
        if($request->has('code')){
            if(!empty($request->get('code'))) {
                session(['authenticated' => true, 'accessToken' => $request->get('code')]);
                return redirect('/dashboard');
            } else {
                \Log::info('Token is not comming from api server');
                $slug = "";
                if(!session()->has('customer')){ 
                    $slug = session('customer');
                }
                return redirect("/$slug");
            }
        }
        return redirect("/");
    }

    public function ehrList(Request $request)
    {
        if (!session()->has('customer')) {
            return $this->checkCustomer();
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, env('API_URL') . "ehr/list");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        $responseData = [];

        if (curl_errno($ch) || $httpCode >= 400) {
            \Log::error('CURL Error: ' . curl_error($ch) . ' | HTTP Code: ' . $httpCode);
        } else {
            $decoded = json_decode($response, true);
            $responseData = $decoded['data'] ?? [];
        }

        curl_close($ch);

        return view('ehrlist', compact('responseData'));
    }

    public function logout()
    {
        $slug = session('customer');
        session()->flush();
        session(['customer' => $slug], Carbon::now()->addYear());
        return redirect("/$slug");
    }
}
