<?php

namespace App\Http\Controllers\VendorShip;

use App\Http\Controllers\Controller;
use App\Models\BalanceLog;
use App\Models\IncomeHistory;
use App\Models\User;
use App\Models\VendorOrder;
use App\Models\VendorProfile;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VendorDashboardController extends Controller
{
    public function profile()
    {
        $profile = VendorProfile::where('user_id', auth()->id())->first();

        if (!$profile) {
            return redirect()->route('vendor-ship.apply');
        }

        if ($profile->status !== 'approved') {
            return view('vendor_ship.pending', compact('profile'));
        }

        return view('vendor_ship.profile', compact('profile'));
    }

    public function orders(Request $request)
    {
        $profile = $this->approvedProfile();
        if (!$profile) {
            return redirect()->route('vendor-ship.profile');
        }

        $base = VendorOrder::where('vendor_profile_id', $profile->id);

        $todayStart = Carbon::today();
        $todayEnd = Carbon::today()->endOfDay();
        $yesterdayStart = Carbon::yesterday()->startOfDay();
        $yesterdayEnd = Carbon::yesterday()->endOfDay();
        $last7Start = Carbon::now()->subDays(6)->startOfDay();
        $last30Start = Carbon::now()->subDays(29)->startOfDay();

        $summary = [
            'today' => (clone $base)->whereBetween('created_at', [$todayStart, $todayEnd])->count(),
            'yesterday' => (clone $base)->whereBetween('created_at', [$yesterdayStart, $yesterdayEnd])->count(),
            'last7' => (clone $base)->where('created_at', '>=', $last7Start)->count(),
            'last30' => (clone $base)->where('created_at', '>=', $last30Start)->count(),
            'total' => (clone $base)->count(),
        ];

        $statusCounts = VendorOrder::where('vendor_profile_id', $profile->id)
            ->selectRaw("
                SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status='processing' THEN 1 ELSE 0 END) as processing,
                SUM(CASE WHEN status='delivered' THEN 1 ELSE 0 END) as delivered,
                SUM(CASE WHEN status='cancelled' THEN 1 ELSE 0 END) as cancelled
            ")
            ->first();

        $status = $request->input('status', 'all');
        $allowed = ['all', 'pending', 'processing', 'delivered', 'cancelled'];
        if (!in_array($status, $allowed, true)) {
            $status = 'all';
        }

        $orders = VendorOrder::where('vendor_profile_id', $profile->id)
            ->when($status !== 'all', fn($q) => $q->where('status', $status))
            ->with(['pdOrder:id,customer_name,customer_phone,status'])
            ->latest()
            ->paginate(12)
            ->withQueryString();

        return view('vendor_ship.orders', compact('profile', 'summary', 'statusCounts', 'orders', 'status'));
    }

    public function updateOrderStatus(Request $request, VendorOrder $vendorOrder)
    {
        $profile = $this->approvedProfile();
        if (!$profile || (int) $vendorOrder->vendor_profile_id !== (int) $profile->id) {
            abort(403);
        }

        $data = $request->validate([
            'status' => 'required|in:processing,delivered,cancelled',
            'cancel_reason' => 'nullable|string|max:1000',
        ]);

        if (!in_array($vendorOrder->status, ['pending', 'processing'], true)) {
            return back()->withErrors(['error' => 'Only pending/processing orders can be updated.']);
        }

        if ($vendorOrder->status === 'pending') {
            if (!in_array($data['status'], ['processing', 'cancelled'], true)) {
                return back()->withErrors(['error' => 'Invalid status transition for pending order.']);
            }
            if ($data['status'] === 'cancelled' && blank($data['cancel_reason'])) {
                return back()->withErrors(['error' => 'Cancel reason is required.']);
            }
        }

        if ($vendorOrder->status === 'processing') {
            if (!in_array($data['status'], ['delivered', 'cancelled'], true)) {
                return back()->withErrors(['error' => 'Invalid status transition for processing order.']);
            }
            if ($data['status'] === 'cancelled' && blank($data['cancel_reason'])) {
                return back()->withErrors(['error' => 'Cancel reason is required.']);
            }
            if ($data['status'] === 'delivered' && $vendorOrder->cancellation_requested_at && empty($vendorOrder->cancellation_response)) {
                return back()->withErrors(['error' => 'Cancel request is pending user response.']);
            }
            if ($data['status'] === 'cancelled' && $vendorOrder->cancellation_requested_at && empty($vendorOrder->cancellation_response)) {
                return back()->withErrors(['error' => 'Cancel request already pending.']);
            }
        }

        DB::transaction(function () use ($vendorOrder, $data) {
            $vendorOrder = VendorOrder::with('pdOrder.product')->lockForUpdate()->findOrFail($vendorOrder->id);
            if (!in_array($vendorOrder->status, ['pending', 'processing'], true)) {
                return;
            }

            if ($vendorOrder->status === 'pending') {
                if ($data['status'] === 'processing') {
                    $vendorOrder->status = 'processing';
                    $vendorOrder->save();
                    if ($vendorOrder->pdOrder) {
                        $vendorOrder->pdOrder->status = 'processing';
                        $vendorOrder->pdOrder->save();
                    }
                    return;
                }

                if ($data['status'] === 'cancelled') {
                    $vendorOrder->status = 'cancelled';
                    $vendorOrder->cancel_reason = trim((string) $data['cancel_reason']);
                    $vendorOrder->cancellation_requested_at = null;
                    $vendorOrder->cancellation_response = null;
                    $vendorOrder->save();
                    if ($vendorOrder->pdOrder) {
                        $vendorOrder->pdOrder->status = 'rejected';
                        $vendorOrder->pdOrder->save();
                    }
                    return;
                }

                return;
            }

            if ($vendorOrder->status === 'processing') {
                if ($data['status'] === 'delivered') {
                    $vendorOrder->status = 'delivered';
                    $vendorOrder->save();
                    if ($vendorOrder->pdOrder) {
                        $vendorOrder->pdOrder->status = 'completed';
                        $vendorOrder->pdOrder->save();

                        $user = User::lockForUpdate()->find($vendorOrder->pdOrder->user_id);
                        $credit = (float) $vendorOrder->pdOrder->earn_total;
                        if ($user && $credit > 0) {
                            $user->balance = (float) ($user->balance ?? 0) + $credit;
                            $user->save();

                            BalanceLog::create([
                                'user_id' => $user->id,
                                'amount' => $credit,
                            ]);

                            $title = optional($vendorOrder->pdOrder->product)->title ?? 'Unknown Product';
                            IncomeHistory::create([
                                'user_id' => $user->id,
                                'source' => 'pd_order',
                                'amount' => $credit,
                                'description' => 'Order #' . $vendorOrder->pdOrder->id . ' completed for "' . $title . '". Profit added: Tk ' . number_format($credit, 2) . '.',
                            ]);
                        }
                    }
                    return;
                }

                if ($data['status'] === 'cancelled') {
                    $vendorOrder->cancel_reason = trim((string) $data['cancel_reason']);
                    $vendorOrder->cancellation_requested_at = now();
                    $vendorOrder->cancellation_response = null;
                    $vendorOrder->save();
                    return;
                }

                return;
            }
        });

        if ($vendorOrder->status === 'processing' && $data['status'] === 'cancelled') {
            return back()->with('success', 'Cancel request sent to user. Waiting for user response.');
        }

        return back()->with('success', 'Order status updated.');
    }

    public function updateTracking(Request $request, VendorOrder $vendorOrder)
    {
        $profile = $this->approvedProfile();
        if (!$profile || (int) $vendorOrder->vendor_profile_id !== (int) $profile->id) {
            abort(403);
        }

        $data = $request->validate([
            'tracking_link' => 'required|url|max:500',
        ]);

        if (!in_array($vendorOrder->status, ['processing', 'delivered'], true)) {
            return back()->withErrors(['error' => 'Tracking link can be updated after processing.']);
        }

        $vendorOrder->tracking_link = $data['tracking_link'];
        $vendorOrder->save();

        return back()->with('success', 'Tracking link updated.');
    }

    public function showOrder(VendorOrder $vendorOrder)
    {
        $profile = $this->approvedProfile();
        if (!$profile || (int) $vendorOrder->vendor_profile_id !== (int) $profile->id) {
            abort(403);
        }

        $vendorOrder->load([
            'pdOrder' => function ($q) {
                $q->select([
                    'id',
                    'product_id',
                    'qty',
                    'admin_price',
                    'reseller_price',
                    'sale_price',
                    'wholesale_total',
                    'earn_total',
                    'grand_total',
                    'size',
                    'color',
                    'customer_name',
                    'customer_phone',
                    'alt_phone',
                    'address',
                    'division',
                    'district',
                    'thana',
                    'status',
                    'created_at',
                ])->with([
                    'product:id,title,slug,banner_photo,description,admin_price,reseller_price,delivery_charge,delivery_payment_type',
                    'product.images:id,product_id,photo,sort_order',
                ]);
            },
        ]);

        return view('vendor_ship.order_show', [
            'profile' => $profile,
            'vendorOrder' => $vendorOrder,
            'pdOrder' => $vendorOrder->pdOrder,
        ]);
    }

    private function approvedProfile(): ?VendorProfile
    {
        return VendorProfile::where('user_id', auth()->id())
            ->where('status', 'approved')
            ->first();
    }
}
