<?php

namespace App\Controllers;

class Auth extends BaseController
{
    public function login()
    {
        $session = session();
        if ($session->get('access_token')) {
            return redirect()->to('/report');
        }
        return view('login');
    }

    public function doLogin()
    {
        $email = trim((string) $this->request->getPost('email'));
        $password = (string) $this->request->getPost('password');

        if ($email === '' || $password === '') {
            return redirect()->back()->withInput()->with('error', 'Email dan password wajib diisi.');
        }

        $payload = [
            'email' => $email,
            'password' => $password,
        ];

        $options = [
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($payload),
            'http_errors' => false,
            'timeout' => 10,
        ];

        try {
            $client = service('curlrequest');
            $apiBase = rtrim((string) (env('api.baseURL') ?? env('API_BASE_URL') ?? 'http://10.210.101.8/api'), '/');
            $loginUrl = $apiBase . '/token/get';
            $response = $client->post($loginUrl, $options);
        } catch (\Throwable $e) {
            return redirect()->back()->withInput()->with('error', 'Gagal menghubungi server otentikasi.');
        }

        $status = $response->getStatusCode();
        $body = (string) $response->getBody();
        $json = json_decode($body, true);

        if ($status === 200 && is_array($json) && ($json['success'] ?? false) && isset($json['data']['access_token'])) {
            $session = session();
            $expiresIn = isset($json['data']['expires_in']) ? (int) $json['data']['expires_in'] : null;
            $session->set([
                'access_token' => $json['data']['access_token'],
                'token_type' => $json['data']['token_type'] ?? 'bearer',
                'token_expires_in' => $expiresIn,
                'token_expires_at' => $expiresIn ? (time() + $expiresIn) : null,
                'user_email' => $email,
            ]);
            return redirect()->to('/report');
        }

        $message = is_array($json) && isset($json['message']) ? (string) $json['message'] : 'Login gagal.';
        return redirect()->back()->withInput()->with('error', $message);
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }
}
