<?php

namespace App\Http\Controllers\Creator;

use App\Http\Controllers\Controller;
use App\Models\Proposal;
use App\Models\ProposalComment;
use Illuminate\Http\Request;

class ProposalController extends Controller
{
    /**
     * Display a listing of proposals
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $proposals = Proposal::where('creator_id', auth()->id())
            ->with('brand')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
            
        return view('creator.proposals.index', compact('proposals'));
    }
    
    /**
     * Show the form for creating a new proposal
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // Get the campaign if specified
        $campaign = null;
        if (request()->has('campaign')) {
            $campaign = \App\Models\Campaign::find(request()->get('campaign'));
        }
        
        return view('creator.proposals.create', compact('campaign'));
    }
    
    /**
     * Display the specified proposal
     *
     * @param  \App\Models\Proposal  $proposal
     * @return \Illuminate\Http\Response
     */
    public function show(Proposal $proposal)
    {
        // Ensure the proposal belongs to the authenticated creator
        if ($proposal->creator_id !== auth()->id()) {
            abort(403);
        }
        
        $proposal->load('brand');
        
        return view('creator.proposals.show', compact('proposal'));
    }
    
    /**
     * Store a newly created proposal
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'brand_id' => 'required|exists:brands,id',
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'type' => 'required|in:Collaboration,Sponsored Post,Affiliate,Long-term Partnership',
            'budget' => 'nullable|numeric|min:0',
            'duration' => 'nullable|string|max:255',
            'deliverables' => 'nullable|array',
            'deliverables.*' => 'string',
            'attachment' => 'nullable|file|mimes:pdf,doc,docx|max:2048',
        ]);
        
        // Handle file upload
        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('proposals', 'public');
        }
        
        // Create the proposal
        $proposal = new Proposal([
            'brand_id' => $validated['brand_id'],
            'creator_id' => auth()->id(),
            'title' => $validated['title'],
            'message' => $validated['message'],
            'type' => $validated['type'],
            'budget' => $validated['budget'] ?? null,
            'duration' => $validated['duration'] ?? null,
            'deliverables' => $validated['deliverables'] ?? null,
            'attachment_path' => $attachmentPath,
            'status' => 'sent',
        ]);
        
        $proposal->save();
        
        // Send notification to brand (implementation depends on your notification system)
        // $proposal->brand->notify(new \App\Notifications\ProposalReceived($proposal));
        
        return redirect()->route('creator.proposals.show', $proposal)->with('success', 'Proposal sent successfully!');
    }
    
    /**
     * Store a new comment on a proposal
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Proposal  $proposal
     * @return \Illuminate\Http\Response
     */
    public function storeComment(Request $request, Proposal $proposal)
    {
        // Ensure the proposal belongs to the authenticated creator
        if ($proposal->creator_id !== auth()->id()) {
            abort(403);
        }
        
        $validated = $request->validate([
            'message' => 'required|string',
            'attachment' => 'nullable|file|mimes:pdf,doc,docx,jpg,png|max:2048',
            'parent_id' => 'nullable|exists:proposal_comments,id',
        ]);
        
        // Handle file upload
        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('proposal_comments', 'public');
        }
        
        // Create the comment
        $comment = new ProposalComment([
            'proposal_id' => $proposal->id,
            'user_id' => auth()->id(),
            'parent_id' => $validated['parent_id'] ?? null,
            'message' => $validated['message'],
            'attachment_path' => $attachmentPath,
            'is_internal' => false, // Creator comments are not internal
        ]);
        
        $comment->save();
        
        return redirect()->back()->with('success', 'Comment added successfully!');
    }
    
    /**
     * Get comments for a proposal as JSON
     *
     * @param  \App\Models\Proposal  $proposal
     * @return \Illuminate\Http\JsonResponse
     */
    public function comments(Proposal $proposal)
    {
        // Ensure the proposal belongs to the authenticated creator
        if ($proposal->creator_id !== auth()->id()) {
            abort(403);
        }
        
        $comments = $proposal->comments()
            ->with('user')
            ->where('parent_id', null) // Only top-level comments
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function ($comment) {
                return [
                    'id' => $comment->id,
                    'user' => [
                        'name' => $comment->user->name,
                        'avatar' => $comment->user->avatar_url ?? asset('vendor/adminlte/dist/img/user2-160x160.jpg'),
                    ],
                    'message' => $comment->message,
                    'attachment_path' => $comment->attachment_path,
                    'created_at' => $comment->created_at->format('M j, Y H:i'),
                    'is_internal' => $comment->is_internal,
                    'replies' => $comment->children()
                        ->with('user')
                        ->orderBy('created_at', 'asc')
                        ->get()
                        ->map(function ($reply) {
                            return [
                                'id' => $reply->id,
                                'user' => [
                                    'name' => $reply->user->name,
                                    'avatar' => $reply->user->avatar_url ?? asset('vendor/adminlte/dist/img/user2-160x160.jpg'),
                                ],
                                'message' => $reply->message,
                                'attachment_path' => $reply->attachment_path,
                                'created_at' => $reply->created_at->format('M j, Y H:i'),
                                'is_internal' => $reply->is_internal,
                            ];
                        }),
                ];
            });
        
        return response()->json($comments);
    }
}