<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Config\Database;

class SearchController extends Controller
{
    public function search(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $q = $_GET['q'] ?? '';
        if (strlen($q) < 2)
            Response::success([]);

        $db = Database::getInstance();
        $results = [
            'customers' => [],
            'products' => [],
            'invoices' => []
        ];

        // Search Customers
        $stmt = $db->prepare("SELECT id, name, company_name as subtext, 'customer' as type FROM customers 
                             WHERE tenant_id = ? AND (name LIKE ? OR company_name LIKE ? OR email LIKE ?) LIMIT 5");
        $stmt->execute([$tenantId, "%$q%", "%$q%", "%$q%"]);
        $results['customers'] = $stmt->fetchAll();

        // Search Products
        $stmt = $db->prepare("SELECT id, name, sku as subtext, 'product' as type FROM products 
                             WHERE tenant_id = ? AND (name LIKE ? OR sku LIKE ?) LIMIT 5");
        $stmt->execute([$tenantId, "%$q%", "%$q%"]);
        $results['products'] = $stmt->fetchAll();

        // Search Invoices
        $stmt = $db->prepare("SELECT i.id, i.invoice_number as name, c.name as subtext, 'invoice' as type 
                             FROM invoices i JOIN customers c ON i.customer_id = c.id 
                             WHERE i.tenant_id = ? AND (i.invoice_number LIKE ? OR c.name LIKE ?) LIMIT 5");
        $stmt->execute([$tenantId, "%$q%", "%$q%"]);
        $results['invoices'] = $stmt->fetchAll();

        Response::success($results);
    }

    public function health(): void
    {
        Response::success([
            'status' => 'healthy',
            'timestamp' => date('c'),
            'version' => '1.0.0',
            'php' => PHP_VERSION,
            'db' => 'connected',
            'tenant_id' => (int) ($_REQUEST['tenant_id'] ?? 0)
        ]);
    }
}
