<?php
class NotificationController {
    public function index(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();

        $tid = Auth::tenantId();
        
        // Get notifications for current tenant
        $stmt = db()->prepare("
            SELECT * FROM notifications 
            WHERE tenant_id = ? 
            ORDER BY created_at DESC 
            LIMIT 50
        ");
        $stmt->execute([$tid]);
        $notifications = $stmt->fetchAll();

        // Get unread count
        $stmt = db()->prepare("
            SELECT COUNT(*) FROM notifications 
            WHERE tenant_id = ? AND is_read = 0
        ");
        $stmt->execute([$tid]);
        $unreadCount = $stmt->fetchColumn();

        $pageTitle = 'Notifications';
        ob_start();
        include APP_ROOT . '/views/tenant/notifications/index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }

    public function markRead(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();

        $id = (int)($_POST['id'] ?? 0);
        $tid = Auth::tenantId();

        $stmt = db()->prepare("
            UPDATE notifications 
            SET is_read = 1 
            WHERE id = ? AND tenant_id = ?
        ");
        $stmt->execute([$id, $tid]);

        // Return JSON response for AJAX requests
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
            exit;
        }

        redirect('notifications');
    }

    public function markAllRead(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();

        $tid = Auth::tenantId();

        $stmt = db()->prepare("
            UPDATE notifications 
            SET is_read = 1 
            WHERE tenant_id = ? AND is_read = 0
        ");
        $stmt->execute([$tid]);

        // Return JSON response for AJAX requests
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
            exit;
        }

        flash('success', 'All notifications marked as read');
        redirect('notifications');
    }

    public function create(array $data): int {
        $stmt = db()->prepare("
            INSERT INTO notifications (tenant_id, type, title, message, reference_id, reference_type, user_id) 
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            Auth::tenantId(),
            $data['type'],
            $data['title'],
            $data['message'],
            $data['reference_id'] ?? null,
            $data['reference_type'] ?? null,
            $data['user_id'] ?? null
        ]);
        return (int)db()->lastInsertId();
    }

    public static function getUnreadCount(): int {
        $tid = Auth::tenantId();
        $stmt = db()->prepare("
            SELECT COUNT(*) FROM notifications 
            WHERE tenant_id = ? AND is_read = 0
        ");
        $stmt->execute([$tid]);
        return (int)$stmt->fetchColumn();
    }

    public static function createLowStockAlert(int $productId, string $productName, int $currentStock, int $alertThreshold): void {
        $data = [
            'type' => 'low_stock',
            'title' => 'Low Stock Alert',
            'message' => "Product '{$productName}' is running low on stock. Current: {$currentStock}, Threshold: {$alertThreshold}",
            'reference_id' => $productId,
            'reference_type' => 'product'
        ];
        
        $controller = new self();
        $controller->create($data);
    }

    public static function createExpiryAlert(int $batchId, string $productName, string $batchNo, string $expiryDate): void {
        $data = [
            'type' => 'expiry',
            'title' => 'Product Expiring Soon',
            'message' => "Batch '{$batchNo}' for '{$productName}' expires on {$expiryDate}",
            'reference_id' => $batchId,
            'reference_type' => 'batch'
        ];
        
        $controller = new self();
        $controller->create($data);
    }

    public static function createSaleNotification(int $saleId, float $total, string $customerName): void {
        $data = [
            'type' => 'sale',
            'title' => 'New Sale Recorded',
            'message' => "Sale of {$total} completed for {$customerName}",
            'reference_id' => $saleId,
            'reference_type' => 'sale'
        ];
        
        $controller = new self();
        $controller->create($data);
    }

    public static function createPurchaseNotification(int $purchaseId, float $total, string $supplierName): void {
        $data = [
            'type' => 'purchase',
            'title' => 'New Purchase Recorded',
            'message' => "Purchase of {$total} completed from {$supplierName}",
            'reference_id' => $purchaseId,
            'reference_type' => 'purchase'
        ];
        
        $controller = new self();
        $controller->create($data);
    }

    public function delete(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();

        $id = (int)($_POST['id'] ?? 0);
        $tid = Auth::tenantId();

        $stmt = db()->prepare("
            DELETE FROM notifications 
            WHERE id = ? AND tenant_id = ?
        ");
        $stmt->execute([$id, $tid]);

        // Return JSON response for AJAX requests
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
            exit;
        }

        redirect('notifications');
    }

    public static function cleanupOldNotifications(): void {
        // Delete notifications older than 30 days
        $stmt = db()->prepare("
            DELETE FROM notifications 
            WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
        ");
        $stmt->execute();
    }
}
