<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Config\Database;
use App\Utils\JWT;
use App\Utils\Env;
use PDO;

class AdminAuthController extends Controller {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }

    public function login() {
        $input = $this->input();
        $this->validate($input, [
            'email' => 'required',
            'password' => 'required'
        ]);

        $stmt = $this->db->prepare("SELECT * FROM admin_users WHERE email = ?");
        $stmt->execute([$input['email']]);
        $admin = $stmt->fetch();

        if (!$admin || !password_verify($input['password'], $admin['password_hash'])) {
            $this->json(['error' => 'Invalid credentials'], 401);
        }

        $payload = [
            'iss' => Env::get('JWT_ISSUER', 'anon-chat'),
            'sub' => $admin['id'],
            'role' => $admin['role'],
            'iat' => time(),
            'exp' => time() + (60 * 60 * 24) // 1 day
        ];
        $token = JWT::encode($payload, Env::get('JWT_SECRET'));

        $this->json(['token' => $token, 'admin' => [
            'id' => $admin['id'],
            'email' => $admin['email'],
            'role' => $admin['role']
        ]]);
    }

    public function logout() {
        $this->json(['message' => 'Logged out']);
    }
}
