<?php
namespace App\Controllers\Api;

use Core\Controller;

class AuthApiController extends Controller
{
    public function login(): void
    {
        $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $email    = filter_var($input['email'] ?? '', FILTER_SANITIZE_EMAIL);
        $password = $input['password'] ?? '';

        if (!$email || !$password) {
            $this->json(['success' => false, 'message' => 'Email and password required.'], 400);
            return;
        }

        $user = $this->db->fetch(
            "SELECT u.*, r.name AS role_name FROM users u JOIN roles r ON r.id=u.role_id WHERE u.email=? AND u.status='active'",
            [$email]
        );

        if (!$user || !password_verify($password, $user['password'])) {
            $this->json(['success' => false, 'message' => 'Invalid credentials.'], 401);
            return;
        }

        $token   = $this->generateJwt($user);
        $refresh = bin2hex(random_bytes(32));

        $this->db->insert('api_tokens', [
            'user_id'       => $user['id'],
            'token'         => $token,
            'refresh_token' => hash('sha256', $refresh),
            'expires_at'    => date('Y-m-d H:i:s', time() + 86400),
            'created_at'    => date('Y-m-d H:i:s'),
        ]);

        $this->json([
            'success'       => true,
            'token'         => $token,
            'refresh_token' => $refresh,
            'expires_in'    => 86400,
            'user' => [
                'id'    => $user['id'],
                'name'  => $user['first_name'] . ' ' . $user['last_name'],
                'email' => $user['email'],
                'role'  => $user['role_name'],
            ],
        ]);
    }

    public function refresh(): void
    {
        $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $refreshToken = $input['refresh_token'] ?? '';
        $hashed = hash('sha256', $refreshToken);
        $record = $this->db->fetch("SELECT * FROM api_tokens WHERE refresh_token=? AND expires_at > NOW()", [$hashed]);
        if (!$record) {
            $this->json(['success' => false, 'message' => 'Invalid or expired refresh token.'], 401);
            return;
        }
        $user  = $this->db->fetch("SELECT u.*, r.name AS role_name FROM users u JOIN roles r ON r.id=u.role_id WHERE u.id=?", [$record['user_id']]);
        $token = $this->generateJwt($user);
        $this->db->update('api_tokens', ['token' => $token, 'expires_at' => date('Y-m-d H:i:s', time() + 86400)], 'id=?', [$record['id']]);
        $this->json(['success' => true, 'token' => $token, 'expires_in' => 86400]);
    }

    public function logout(): void
    {
        $token = $this->getBearerToken();
        if ($token) {
            $this->db->delete('api_tokens', 'token=?', [$token]);
        }
        $this->json(['success' => true, 'message' => 'Logged out.']);
    }

    private function generateJwt(array $user): string
    {
        $header  = base64_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
        $payload = base64_encode(json_encode([
            'sub'  => $user['id'],
            'name' => $user['first_name'] . ' ' . $user['last_name'],
            'role' => $user['role_name'],
            'iat'  => time(),
            'exp'  => time() + 86400,
        ]));
        $secret    = defined('APP_NAME') ? APP_NAME . '_secret_key_2024' : 'zabibu_secret';
        $signature = base64_encode(hash_hmac('sha256', "$header.$payload", $secret, true));
        return "$header.$payload.$signature";
    }

    private function getBearerToken(): ?string
    {
        $headers = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (preg_match('/Bearer\s+(.+)/i', $headers, $m)) return $m[1];
        return null;
    }
}
