<?php
class APIController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $cid = Auth::user()['company_id'];
        $apiKeys = $this->db->fetchAll("SELECT * FROM api_keys WHERE company_id=? AND deleted_at IS NULL ORDER BY created_at DESC", [$cid]);
        $webhooks = $this->db->fetchAll("SELECT * FROM webhooks WHERE company_id=? AND deleted_at IS NULL ORDER BY created_at DESC", [$cid]);
        require 'app/views/api/index.php';
    }

    public function createKey() {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        $key = 'rr_' . bin2hex(random_bytes(24));
        $this->db->insert('api_keys', ['company_id' => $cid, 'name' => $_POST['name'] ?? 'API Key', 'api_key' => hash('sha256', $key), 'prefix' => substr($key, 0, 10), 'permissions' => json_encode($_POST['permissions'] ?? ['read']), 'created_by' => Auth::user()['id']]);
        flash('success', 'API key created: ' . $key . ' — Copy it now, it won\'t be shown again.'); redirect('?page=api');
    }

    public function deleteKey($id) {
        CSRF::verify();
        $this->db->softDelete('api_keys', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'API key revoked.'); redirect('?page=api');
    }

    public function createWebhook() {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        $this->db->insert('webhooks', ['company_id' => $cid, 'url' => $_POST['url'], 'events' => json_encode($_POST['events'] ?? []), 'secret' => bin2hex(random_bytes(16)), 'status' => 'active']);
        flash('success', 'Webhook created.'); redirect('?page=api');
    }

    public function deleteWebhook($id) {
        CSRF::verify();
        $this->db->softDelete('webhooks', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Webhook deleted.'); redirect('?page=api');
    }
}
