<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardApiController extends Controller
{
    /**
     * Get list of orders for the authenticated user.
     */
    public function orders(Request $request)
    {
        $userId = Auth::id();
        
        $orders = Order::where('user_id', $userId)
            ->with(['items.product'])
            ->orderByDesc('created_at')
            ->paginate(10);

        return response()->json($orders);
    }

    /**
     * Get details of a specific order.
     */
    public function orderDetails(Request $request, $orderId)
    {
        $userId = Auth::id();

        $order = Order::where('user_id', $userId)
            ->where('id', $orderId)
            ->with(['items.product', 'history'])
            ->firstOrFail();

        return response()->json([
            'order' => $order,
        ]);
    }

    /**
     * Get list of active/available coupons.
     */
    public function coupons(Request $request)
    {
        $now = now();
        $coupons = \App\Models\Coupon::where('is_active', true)
            ->where(function ($query) use ($now) {
                $query->whereNull('starts_at')
                    ->orWhere('starts_at', '<=', $now);
            })
            ->where(function ($query) use ($now) {
                $query->whereNull('expires_at')
                    ->orWhere('expires_at', '>=', $now);
            })
            ->orderByDesc('created_at')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $coupons,
        ]);
    }

    /**
     * Create or update a customer address.
     */
    public function saveAddress(Request $request)
    {
        $userId = Auth::id();

        $request->validate([
            'id' => 'nullable|integer',
            'address_type' => 'required|string',
            'street' => 'required|string',
            'city' => 'required|string',
            'upazila' => 'required|string',
            'zip' => 'required|string',
            'phone' => 'required|string|max:20',
        ]);

        $streetCombined = $request->street;
        if ($request->upazila) {
            $streetCombined = $request->street . ', ' . $request->upazila;
        }

        if ($request->id) {
            $address = \App\Models\CustomerAddress::where('customer_id', $userId)
                ->where('id', $request->id)
                ->firstOrFail();

            $address->update([
                'street' => $streetCombined,
                'city' => $request->city,
                'zip' => $request->zip,
                'country' => $request->address_type,
                'phone' => $request->phone,
            ]);
        } else {
            $address = \App\Models\CustomerAddress::create([
                'customer_id' => $userId,
                'street' => $streetCombined,
                'city' => $request->city,
                'zip' => $request->zip,
                'country' => $request->address_type,
                'phone' => $request->phone,
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Address saved successfully!',
            'address' => $address,
        ]);
    }

    /**
     * Delete a customer address.
     */
    public function deleteAddress(Request $request, $id)
    {
        $userId = Auth::id();
        $address = \App\Models\CustomerAddress::where('customer_id', $userId)
            ->where('id', $id)
            ->firstOrFail();

        $address->delete();

        return response()->json([
            'success' => true,
            'message' => 'Address deleted successfully!',
        ]);
    }

    /**
     * Get list of payments/transactions and stats for the authenticated user.
     */
    public function payments(Request $request)
    {
        $userId = Auth::id();

        // Get all transactions for the user's orders
        $query = \App\Models\Transaction::whereHas('order', function ($q) use ($userId) {
            $q->where('user_id', $userId);
        });

        // Calculate stats (only successful ones)
        $successfulQuery = clone $query;
        $successfulQuery->where('status', 'success');

        $now = \Carbon\Carbon::now();
        
        $thisMonthSpent = (float) (clone $successfulQuery)
            ->whereMonth('created_at', $now->month)
            ->whereYear('created_at', $now->year)
            ->sum('amount');

        $lastSixMonthsSpent = (float) (clone $successfulQuery)
            ->where('created_at', '>=', $now->copy()->subMonths(6))
            ->sum('amount');

        $totalSpent = (float) (clone $successfulQuery)
            ->sum('amount');

        // Get list of all transactions (successful, failed, pending etc.)
        $transactions = $query->with('order')
            ->orderByDesc('created_at')
            ->paginate(10);

        return response()->json([
            'success' => true,
            'stats' => [
                'this_month_spent' => $thisMonthSpent,
                'last_six_months_spent' => $lastSixMonthsSpent,
                'total_spent' => $totalSpent,
            ],
            'transactions' => $transactions,
        ]);
    }

    /**
     * Get reviews submitted by the authenticated user.
     */
    public function reviews(Request $request)
    {
        $userId = Auth::id();
        $reviews = \App\Models\ProductReview::where('user_id', $userId)
            ->with('product')
            ->orderByDesc('created_at')
            ->paginate(10);

        return response()->json([
            'success' => true,
            'reviews' => $reviews,
        ]);
    }

    /**
     * Submit a new review for a product.
     */
    public function submitReview(Request $request)
    {
        $userId = Auth::id();

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

        $review = \App\Models\ProductReview::updateOrCreate(
            [
                'user_id' => $userId,
                'product_id' => $request->product_id,
            ],
            [
                'rating' => $request->rating,
                'comment' => $request->comment,
                'status' => 'approved', // auto-approve for now
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Review submitted successfully!',
            'review' => $review,
        ]);
    }

    /**
     * Get support tickets for the authenticated user.
     */
    public function tickets(Request $request)
    {
        $userId = Auth::id();
        $tickets = \App\Models\SupportTicket::where('user_id', $userId)
            ->orderByDesc('created_at')
            ->paginate(10);

        return response()->json([
            'success' => true,
            'tickets' => $tickets,
        ]);
    }

    /**
     * Submit a new support ticket.
     */
    public function submitTicket(Request $request)
    {
        $userId = Auth::id();

        $request->validate([
            'title' => 'required|string|max:255',
            'topic' => 'required|string|max:255',
            'description' => 'required|string',
            'attachment' => 'nullable|file|image|max:5120',
        ]);

        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/tickets'), $filename);
            $attachmentPath = '/uploads/tickets/' . $filename;
        }

        $ticket = \App\Models\SupportTicket::create([
            'user_id' => $userId,
            'title' => $request->title,
            'topic' => $request->topic,
            'description' => $request->description,
            'attachment' => $attachmentPath,
            'status' => 'pending',
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Support ticket created successfully!',
            'ticket' => $ticket,
        ]);
    }

    /**
     * Update customer profile details (name, avatar, and primary address).
     */
    public function updateProfile(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'name' => 'required|string|max:255',
            'avatar' => 'nullable|image|max:5120',
            'address' => 'nullable|string|max:500',
        ]);

        $user->name = $request->name;

        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/avatars'), $filename);
            $user->avatar = '/uploads/avatars/' . $filename;
        }

        $user->save();

        if ($request->has('address') && $request->address !== null) {
            $address = $user->addresses()->first();
            if ($address) {
                $address->update([
                    'street' => $request->address,
                ]);
            } else {
                $user->addresses()->create([
                    'street' => $request->address,
                    'zip' => '1000',
                    'city' => 'Dhaka',
                    'country' => 'Bangladesh',
                ]);
            }
        }

        // Refresh user addresses relationship
        $user->load('addresses');

        return response()->json([
            'success' => true,
            'message' => 'Profile updated successfully!',
            'user' => $user,
        ]);
    }

    /**
     * Update customer phone number.
     */
    public function updatePhone(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'phone' => 'required|string|max:20',
        ]);

        $user->phone = $request->phone;
        $user->save();

        return response()->json([
            'success' => true,
            'message' => 'Phone number updated successfully!',
            'user' => $user,
        ]);
    }

    /**
     * Update customer email address.
     */
    public function updateEmail(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
        ]);

        $user->email = $request->email;
        $user->save();

        return response()->json([
            'success' => true,
            'message' => 'Email address updated successfully!',
            'user' => $user,
        ]);
    }

    /**
     * Revoke third-party linked account.
     */
    public function revokeSocial(Request $request)
    {
        return response()->json([
            'success' => true,
            'message' => 'Third-party linked account revoked successfully!',
        ]);
    }
}

