<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Poke;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PokeController extends Controller
{
    /**
     * Display pokes dashboard
     */
    public function dashboard()
    {
        $userId = Auth::id();
        
        $receivedPokes = Poke::where('receiver_id', $userId)
            ->with('sender')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();
            
        $sentPokes = Poke::where('sender_id', $userId)
            ->with('receiver')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();
            
        $unreadCount = Poke::where('receiver_id', $userId)
            ->where('is_read', false)
            ->count();
            
        $topPokers = Poke::where('receiver_id', $userId)
            ->select('sender_id')
            ->selectRaw('count(*) as poke_count')
            ->groupBy('sender_id')
            ->orderBy('poke_count', 'desc')
            ->limit(5)
            ->with('sender')
            ->get();
            
        return view('front_end.pages.pokes.dashboard', compact(
            'receivedPokes',
            'sentPokes',
            'unreadCount',
            'topPokers'
        ));
    }
    
    /**
     * Display received pokes
     */
    public function received()
    {
        $pokes = Poke::where('receiver_id', Auth::id())
            ->with('sender')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
            
        return view('social.pokes.received', compact('pokes'));
    }
    
    /**
     * Display sent pokes
     */
    public function sent()
    {
        $pokes = Poke::where('sender_id', Auth::id())
            ->with('receiver')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
            
        return view('social.pokes.sent', compact('pokes'));
    }
    
    /**
     * Send a poke to a user
     */
    public function send(Request $request, $userId)
    {
        $user = User::findOrFail($userId);
        
        // Don't allow sending pokes to yourself
        if (Auth::id() == $user->id) {
            return redirect()->back()
                ->with('error', 'You cannot poke yourself.');
        }
        
        // Validate message if provided
        $validator = Validator::make($request->all(), [
            'message' => 'nullable|max:150',
        ]);
        
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        
        // Check for spam (no more than 3 pokes to same user within 24 hours)
        $recentPokes = Poke::where('sender_id', Auth::id())
            ->where('receiver_id', $user->id)
            ->where('created_at', '>=', now()->subHours(24))
            ->count();
            
        if ($recentPokes >= 3) {
            return redirect()->back()
                ->with('error', 'You\'ve already poked this user multiple times today. Try again later.');
        }
        
        // Create the poke
        Poke::create([
            'sender_id' => Auth::id(),
            'receiver_id' => $user->id,
            'message' => $request->input('message'),
        ]);
        
        return redirect()->back()
            ->with('success', 'You have poked ' . $user->name . '!');
    }
    
    /**
     * Mark a poke as read
     */
    public function markAsRead($id)
    {
        $poke = Poke::findOrFail($id);
        
        // Check if user owns this poke
        if ($poke->receiver_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'You do not have permission to perform this action.');
        }
        
        $poke->markAsRead();
        
        return redirect()->back()
            ->with('success', 'Poke marked as read.');
    }
    
    /**
     * Mark all pokes as read
     */
    public function markAllAsRead()
    {
        Poke::where('receiver_id', Auth::id())
            ->where('is_read', false)
            ->update([
                'is_read' => true,
                'read_at' => now()
            ]);
            
        return redirect()->back()
            ->with('success', 'All pokes marked as read.');
    }
    
    /**
     * Poke back a user
     */
    public function pokeBack($id)
    {
        $poke = Poke::findOrFail($id);
        
        // Check if user owns this poke
        if ($poke->receiver_id != Auth::id()) {
            return redirect()->back()
                ->with('error', 'You do not have permission to perform this action.');
        }
        
        // Mark original poke as read
        $poke->markAsRead();
        
        // Create a new poke back
        Poke::create([
            'sender_id' => Auth::id(),
            'receiver_id' => $poke->sender_id,
            'message' => 'Poked you back!',
        ]);
        
        return redirect()->back()
            ->with('success', 'You poked ' . $poke->sender->name . ' back!');
    }
}

