<?php
/**
 * API Controller - AJAX endpoints
 * Handles: product search, customer search, notifications, etc.
 */
class ApiController {
    
    /**
     * Search products
     */
    public function searchProducts(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $query = $_GET['q'] ?? '';
        $locationId = $_GET['location_id'] ?? null;
        $tid = Auth::tenantId();
        
        if (strlen($query) < 2) {
            jsonResponse(['results' => []]);
            return;
        }
        
        $sql = "SELECT id, name, sku, product_price as price FROM products 
                WHERE tenant_id = ? AND (name LIKE ? OR sku LIKE ?) 
                AND is_active = 1 LIMIT 20";
        $params = [$tid, "%$query%", "%$query%"];
        
        if ($locationId) {
            $sql = "SELECT p.id, p.name, p.sku, p.product_price as price, 
                           COALESCE(SUM(s.quantity), 0) as stock
                    FROM products p
                    LEFT JOIN stock s ON s.product_id = p.id AND s.location_id = ? AND s.tenant_id = ?
                    WHERE p.tenant_id = ? AND (p.name LIKE ? OR p.sku LIKE ?) 
                    AND p.is_active = 1
                    GROUP BY p.id
                    LIMIT 20";
            array_unshift($params, $locationId, $tid);
        }
        
        $stmt = db()->prepare($sql);
        $stmt->execute($params);
        $results = $stmt->fetchAll();
        
        jsonResponse(['results' => $results]);
    }
    
    /**
     * Get product stock info
     */
    public function productStock(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $productId = (int)($_GET['id'] ?? 0);
        if (!$productId) {
            jsonResponse(['error' => 'Product ID required'], 400);
            return;
        }
        
        $tid = Auth::tenantId();
        
        $stmt = db()->prepare("
            SELECT id, name, sku, batch_tracking, 
                   COALESCE(SUM(s.quantity), 0) as total_stock
            FROM products p
            LEFT JOIN stock s ON s.product_id = p.id AND s.tenant_id = ?
            WHERE p.id = ? AND p.tenant_id = ?
            GROUP BY p.id
        ");
        $stmt->execute([$tid, $productId, $tid]);
        $product = $stmt->fetch();
        
        if (!$product) {
            jsonResponse(['error' => 'Product not found'], 404);
            return;
        }
        
        jsonResponse(['product' => $product]);
    }

    /**
     * Get stock for all products at a specific location
     */
    public function locationProductsStock(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $locationId = (int)($_GET['location_id'] ?? 0);
        if (!$locationId) {
            jsonResponse(['error' => 'Location ID required'], 400);
            return;
        }
        
        $tid = Auth::tenantId();
        
        $stmt = db()->prepare("
            SELECT p.id, COALESCE(SUM(s.quantity), 0) as stock
            FROM products p
            LEFT JOIN stock s ON s.product_id = p.id AND s.location_id = ? AND s.tenant_id = ?
            WHERE p.tenant_id = ? AND p.is_active = 1
            GROUP BY p.id
        ");
        $stmt->execute([$locationId, $tid, $tid]);
        $results = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        jsonResponse(['stock_map' => $results]);
    }
    
    /**
     * Search customers
     */
    public function searchCustomers(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $query = $_GET['q'] ?? '';
        $tid = Auth::tenantId();
        
        if (strlen($query) < 2) {
            jsonResponse(['results' => []]);
            return;
        }
        
        $stmt = db()->prepare("
            SELECT id, name, phone, email 
            FROM customers 
            WHERE tenant_id = ? AND (name LIKE ? OR phone LIKE ? OR email LIKE ?) 
            AND is_active = 1
            LIMIT 20
        ");
        $stmt->execute([$tid, "%$query%", "%$query%", "%$query%"]);
        $results = $stmt->fetchAll();
        
        jsonResponse(['results' => $results]);
    }
    
    /**
     * Search suppliers
     */
    public function searchSuppliers(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $query = $_GET['q'] ?? '';
        $tid = Auth::tenantId();
        
        if (strlen($query) < 2) {
            jsonResponse(['results' => []]);
            return;
        }
        
        $stmt = db()->prepare("
            SELECT id, name, code, phone, email 
            FROM suppliers 
            WHERE tenant_id = ? AND (name LIKE ? OR code LIKE ? OR phone LIKE ?) 
            AND is_active = 1
            LIMIT 20
        ");
        $stmt->execute([$tid, "%$query%", "%$query%", "%$query%"]);
        $results = $stmt->fetchAll();
        
        jsonResponse(['results' => $results]);
    }
    
    /**
     * Get notifications
     */
    public function notifications(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $tid = Auth::tenantId();
        $userId = Auth::userId();
        $limit = (int)($_GET['limit'] ?? 10);
        $page = (int)($_GET['page'] ?? 1);
        $offset = ($page - 1) * $limit;
        
        $stmt = db()->prepare("
            SELECT * FROM notifications 
            WHERE tenant_id = ? AND (user_id = ? OR user_id IS NULL)
            ORDER BY created_at DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$tid, $userId, $limit, $offset]);
        $notifications = $stmt->fetchAll();
        
        $countStmt = db()->prepare("
            SELECT COUNT(*) FROM notifications 
            WHERE tenant_id = ? AND (user_id = ? OR user_id IS NULL)
        ");
        $countStmt->execute([$tid, $userId]);
        $total = (int)$countStmt->fetchColumn();
        
        jsonResponse([
            'notifications' => $notifications,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }
    
    /**
     * Get dashboard stats
     */
    public function dashboardStats(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $tid = Auth::tenantId();
        $startDate = $_GET['start_date'] ?? date('Y-m-01');
        $endDate = $_GET['end_date'] ?? date('Y-m-d');
        
        // Total sales
        $salesStmt = db()->prepare("
            SELECT COUNT(*) as count, COALESCE(SUM(total), 0) as amount
            FROM sales 
            WHERE tenant_id = ? AND DATE(created_at) BETWEEN ? AND ? AND status = 'completed'
        ");
        $salesStmt->execute([$tid, $startDate, $endDate]);
        $sales = $salesStmt->fetch();
        
        // Total purchases
        $purchasesStmt = db()->prepare("
            SELECT COUNT(*) as count, COALESCE(SUM(total), 0) as amount
            FROM purchases 
            WHERE tenant_id = ? AND DATE(created_at) BETWEEN ? AND ? AND status = 'completed'
        ");
        $purchasesStmt->execute([$tid, $startDate, $endDate]);
        $purchases = $purchasesStmt->fetch();
        
        // Product stats
        $productsStmt = db()->prepare("
            SELECT COUNT(*) as total, 
                   SUM(CASE WHEN COALESCE((SELECT SUM(quantity) FROM stock WHERE product_id = products.id AND tenant_id = ?), 0) = 0 THEN 1 ELSE 0 END) as out_of_stock
            FROM products WHERE tenant_id = ?
        ");
        $productsStmt->execute([$tid, $tid]);
        $products = $productsStmt->fetch();
        
        // Revenue
        $revenueStmt = db()->prepare("
            SELECT COALESCE(SUM(total), 0) as total
            FROM sales 
            WHERE tenant_id = ? AND DATE(created_at) BETWEEN ? AND ? AND status = 'completed'
        ");
        $revenueStmt->execute([$tid, $startDate, $endDate]);
        $revenue = (float)$revenueStmt->fetchColumn();
        
        jsonResponse([
            'sales' => $sales,
            'purchases' => $purchases,
            'products' => $products,
            'revenue' => $revenue
        ]);
    }
}
