<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Feedback;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Support\Facades\DB;

class TransactionController extends Controller
{
    public function show(Transaction $transaction)
    {
        // Ensure user is either buyer or seller
        if ($transaction->buyer_id !== auth()->id() && $transaction->seller_id !== auth()->id()) {
            abort(403, 'You are not authorized to view this transaction.');
        }

        $transaction->load(['item.primaryPhoto', 'buyer', 'seller', 'feedback.reviewer']);

        return view('transactions.show', compact('transaction'));
    }

    public function storeFeedback(Request $request, Transaction $transaction)
    {
        if ($transaction->buyer_id !== auth()->id() && $transaction->seller_id !== auth()->id()) {
            abort(403, 'You are not part of this transaction.');
        }

        if ($transaction->status !== 'completed') {
            return back()->with('error', 'You can leave feedback once the transaction is completed.');
        }

        if ($transaction->feedback()->where('reviewer_id', auth()->id())->exists()) {
            return back()->with('error', 'You have already left feedback for this transaction.');
        }

        $validated = $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:1000',
        ]);

        $isSeller = $transaction->seller_id === auth()->id();
        $reviewee = $isSeller ? $transaction->buyer : $transaction->seller;

        Feedback::create([
            'transaction_id' => $transaction->id,
            'reviewer_id' => auth()->id(),
            'reviewee_id' => $reviewee->id,
            'rating' => $validated['rating'],
            'comment' => $validated['comment'] ?? null,
            'type' => $isSeller ? 'seller' : 'buyer',
            'is_public' => true,
        ]);

        $this->refreshRatingAggregates($reviewee);

        return back()->with('success', 'Thanks — your feedback has been posted.');
    }

    /**
     * Keep the denormalized rating/total_reviews columns (shown on public
     * profiles) in sync with the feedback table.
     */
    private function refreshRatingAggregates(User $user): void
    {
        $stats = Feedback::where('reviewee_id', $user->id)
            ->public()
            ->selectRaw('COUNT(*) as total, COALESCE(AVG(rating), 0) as average')
            ->first();

        // forceFill: rating/total_reviews are intentionally not mass-assignable
        $user->forceFill([
            'rating' => round($stats->average, 2),
            'total_reviews' => $stats->total,
        ])->save();
    }

    public function addTracking(Request $request, Transaction $transaction)
    {
        // Ensure user is the seller
        if ($transaction->seller_id !== auth()->id()) {
            abort(403, 'Only the seller can add tracking information.');
        }

        $validated = $request->validate([
            'tracking_number' => 'required|string|max:255'
        ]);

        try {
            DB::beginTransaction();

            $transaction->update([
                'tracking_number' => $validated['tracking_number'],
                'tracking_added_at' => now(),
            ]);

            // Send automatic message to buyer
            $this->sendTrackingNotification($transaction);

            DB::commit();

            return back()->with('success', 'Tracking number added and buyer has been notified!');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Failed to add tracking number. Please try again.');
        }
    }

    public function confirmReceipt(Transaction $transaction)
    {
        // Ensure user is the buyer
        if ($transaction->buyer_id !== auth()->id()) {
            abort(403, 'Only the buyer can confirm receipt.');
        }

        if ($transaction->buyer_confirmed) {
            return back()->with('error', 'You have already confirmed receipt of this item.');
        }

        $transaction->update([
            'buyer_confirmed' => true,
            'buyer_confirmed_at' => now(),
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        // Notify seller that receipt was confirmed
        $transaction->seller->notify(new \App\Notifications\ReceiptConfirmed($transaction));

        return back()->with('success', 'Transaction completed! Thank you for confirming receipt.');
    }

    public function myTransactions()
    {
        $buyerTransactions = auth()->user()->boughtTransactions()
            ->with(['item.primaryPhoto', 'seller'])
            ->latest()
            ->get();

        $sellerTransactions = auth()->user()->soldTransactions()
            ->with(['item.primaryPhoto', 'buyer'])
            ->latest()
            ->get();

        return view('transactions.index', compact('buyerTransactions', 'sellerTransactions'));
    }

    private function sendTrackingNotification(Transaction $transaction)
    {
        // Find existing conversation between buyer and seller for this item
        $conversation = Conversation::where('item_id', $transaction->item_id)
            ->whereHas('participants', function ($query) use ($transaction) {
                $query->where('user_id', $transaction->buyer_id);
            })
            ->whereHas('participants', function ($query) use ($transaction) {
                $query->where('user_id', $transaction->seller_id);
            })
            ->first();

        // Create new conversation if none exists
        if (!$conversation) {
            $conversation = Conversation::create([
                'item_id' => $transaction->item_id,
                'subject' => "Tracking Info: {$transaction->item->title}",
                'last_message_at' => now(),
            ]);

            $conversation->participants()->attach([
                $transaction->seller_id => ['last_read_at' => now()],
                $transaction->buyer_id => ['last_read_at' => null],
            ]);
        }

        // Send tracking message
        Message::create([
            'conversation_id' => $conversation->id,
            'user_id' => $transaction->seller_id,
            'body' => "Good news! Your item \"{$transaction->item->title}\" has shipped.\n\nTracking Number: {$transaction->tracking_number}\n\nPlease confirm receipt on the transaction page once you receive the item.\n\nThank you for your purchase!",
        ]);

        // Update conversation timestamp and mark as unread for buyer
        $conversation->update(['last_message_at' => now()]);
        $conversation->markAsRead($transaction->seller_id);

        // Send email notification to buyer with tracking info
        $transaction->buyer->notify(new \App\Notifications\TrackingInfoNotification($transaction));
    }
}
