<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Space;
use App\Models\SpaceMember;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SpaceController extends Controller
{
    /**
     * Display a listing of all spaces
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = Space::with(['user'])->withCount('members');

        // Filter by search term
        if ($request->has('search') && !empty($request->input('search'))) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%")
                  ->orWhere('topic', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->has('status') && !empty($request->input('status'))) {
            $query->where('status', $request->input('status'));
        }

        // Filter by privacy
        if ($request->has('privacy') && $request->input('privacy') !== '') {
            $query->where('privacy', $request->input('privacy'));
        }

        // Filter by date range
        if ($request->has('date_from') && !empty($request->input('date_from'))) {
            $query->whereDate('created_at', '>=', $request->input('date_from'));
        }
        if ($request->has('date_to') && !empty($request->input('date_to'))) {
            $query->whereDate('created_at', '<=', $request->input('date_to'));
        }

        // Sort by
        switch($request->input('sort')) {
            case 'oldest':
                $query->orderBy('created_at', 'asc');
                break;
            case 'members':
                $query->orderBy('members_count', 'desc');
                break;
            default: // newest
                $query->orderBy('created_at', 'desc');
                break;
        }

        $spaces = $query->paginate(15);

        // Get counts for dashboard
        $totalSpaces = Space::count();
        $activeSpaces = Space::where('status', 'active')->count();
        $completedSpaces = Space::where('status', 'completed')->count();
        $scheduledSpaces = Space::where('status', 'scheduled')->count();

        return view('admin.pages.spaces.index', compact(
            'spaces',
            'totalSpaces',
            'activeSpaces',
            'completedSpaces',
            'scheduledSpaces'
        ));
    }

    /**
     * Display the space details page
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $space = Space::with(['user', 'members.user'])->findOrFail($id);

        // Get space statistics
        $totalMembers = $space->members()->count();
        $totalHosts = $space->members()->where('is_host', 1)->count();
        $totalCoHosts = $space->members()->where('is_cohost', 1)->where('is_host', 0)->count();
        $totalListeners = $space->members()->where('is_host', 0)->where('is_cohost', 0)->count();

        // Get all members with user details
        $members = $space->members()
            ->with('user')
            ->orderBy('is_host', 'desc')
            ->orderBy('is_cohost', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();

        // Get privacy label
        $privacyLabels = [
            1 => 'Public',
            2 => 'Followers Only',
            3 => 'Private'
        ];

        return view('admin.pages.spaces.show', compact(
            'space',
            'totalMembers',
            'totalHosts',
            'totalCoHosts',
            'totalListeners',
            'members',
            'privacyLabels'
        ));
    }
}

