<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Page;
use App\Models\Product;
use App\Models\Customer;
use App\Models\Order;
use App\Models\CrmCard;
use App\Models\Media;

class WorkspaceController extends Controller
{
    /**
     * Get all workspace data for the authenticated user
     */
    public function index(Request $request)
    {
        $user = $request->user();

        // Load user with settings
        $user->load('settings');

        // Get all pages with blocks
        $pages = Page::where('user_id', $user->id)
            ->with(['blocks' => function ($query) {
                $query->orderBy('order');
            }])
            ->get();

        // Get all products
        $products = Product::where('user_id', $user->id)->get();

        // Get all customers
        $customers = Customer::where('user_id', $user->id)->get();

        // Get all orders with relationships
        $orders = Order::where('user_id', $user->id)
            ->with(['customer', 'products'])
            ->get();

        // Get all CRM cards
        $crmCards = CrmCard::where('user_id', $user->id)
            ->with('customer')
            ->get();

        // Get all media
        $media = Media::where('user_id', $user->id)->get();

        return response()->json([
            'currentUser' => $user,
            'settings' => $user->settings,
            'pages' => $pages,
            'products' => $products,
            'customers' => $customers,
            'orders' => $orders,
            'crmCards' => $crmCards,
            'media' => $media,
            'apps' => [
                'crm' => true,
                'recap' => true
            ]
        ]);
    }
}
