<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDocument;
use App\Models\OrderRemark;
use App\Models\ServicePackage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

use App\Services\NotificationService;

class DashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        $orders = Order::where('user_id', $user->id)
            ->with(['service', 'package'])
            ->latest()
            ->take(5)
            ->get();

        $stats = [
            'active'    => Order::where('user_id', $user->id)->whereIn('status', ['pending','in_progress','under_review'])->count(),
            'completed' => Order::where('user_id', $user->id)->where('status', 'completed')->count(),
            'invoices'  => $user->invoices()->where('status', 'sent')->count(),
        ];

        $consultations = $user->consultations()->with('slot')->latest()->take(3)->get();

        return view('user.dashboard', compact('user', 'orders', 'stats', 'consultations'));
    }

    public function orders()
    {
        $orders = Order::where('user_id', auth()->id())
            ->with(['service', 'package'])
            ->latest()
            ->paginate(10);

        return view('user.orders.index', compact('orders'));
    }

    public function orderDetail(Order $order)
    {
        $this->authorize('view', $order);
        $order->load(['service', 'package', 'documents', 'remarks.user', 'timelines', 'invoices']);
        return view('user.orders.show', compact('order'));
    }

    public function uploadDocument(Request $request, Order $order)
    {
        $this->authorize('view', $order);

        $request->validate([
            'document_name' => 'required|string',
            'file'          => 'required|file|max:10240|mimes:pdf,jpg,jpeg,png,doc,docx',
        ]);

        $path = $request->file('file')->store("orders/{$order->id}/documents", 'public');

        $doc = OrderDocument::create([
            'order_id'      => $order->id,
            'document_name' => $request->document_name,
            'status'        => 'pending',
        ]);

        $doc->update([
            'file_path' => $path,
            'status'    => 'uploaded',
        ]);

        NotificationService::notifyAdmins(
            'New Document Uploaded',
            auth()->user()->name . " uploaded a document for " . $order->order_number,
            "/admin/orders/" . $order->id . "/edit",
            'success'
        );

        return back()->with('success', 'Document uploaded successfully!');
    }

    public function addRemark(Request $request, Order $order)
    {
        $this->authorize('view', $order);

        $request->validate(['message' => 'required|string|max:2000']);

        $order->remarks()->create([
            'user_id' => auth()->id(),
            'message' => $request->message,
            'is_admin' => false,
        ]);

        NotificationService::notifyAdmins(
            'New Message from Customer',
            auth()->user()->name . " sent a message on " . $order->order_number,
            "/admin/orders/" . $order->id . "/edit",
            'info'
        );

        return back()->with('success', 'Message sent!');
    }

    public function invoices()
    {
        $invoices = auth()->user()->invoices()->with('order.service')->latest()->paginate(10);
        return view('user.invoices', compact('invoices'));
    }

    public function markNotificationsRead()
    {
        auth()->user()->unreadNotifications->markAsRead();
        return back()->with('success', 'All notifications marked as read');
    }

    public function consultations()
    {
        $consultations = auth()->user()->consultations()->with('slot')->latest()->paginate(10);
        return view('user.consultations', compact('consultations'));
    }

    public function profile()
    {
        $user = auth()->user();
        return view('user.profile', compact('user'));
    }

    public function updateProfile(Request $request)
    {
        $user = auth()->user();

        $request->validate([
            'name'          => 'required|string|max:255',
            'phone'         => 'nullable|string|max:20',
            'cnic'          => 'nullable|string|max:20',
            'address'       => 'nullable|string|max:500',
            'city'          => 'nullable|string|max:100',
            'business_name' => 'nullable|string|max:255',
        ]);

        $user->update($request->only(['name', 'phone', 'cnic', 'address', 'city', 'business_name']));

        return back()->with('success', 'Profile updated successfully!');
    }

    public function placeOrder(Request $request)
    {
        $request->validate([
            'service_package_id' => 'required|exists:service_packages,id',
            'payment_type'       => 'required|in:full,partial',
            'notes'              => 'nullable|string|max:1000',
        ]);

        $package = ServicePackage::with('service')->findOrFail($request->service_package_id);
        $service = $package->service;

        // Calculate amounts
        $totalAmount = $package->price;
        $paidAmount  = 0;
        $paymentStatus = 'unpaid';

        // Handle partial payment logic (25% deposit)
        if ($request->payment_type === 'partial' && $service->allow_partial_payment) {
            $percentage = $service->partial_payment_percentage ?? 25;
            $paidAmount = 0; // We define what is paid vs just what is expected
            // Note: In a real system, we'd trigger the gateway here. 
            // For now, we record the intent and total.
        }

        $order = Order::create([
            'user_id'            => auth()->id(),
            'service_id'         => $service->id,
            'service_package_id' => $package->id,
            'total_amount'       => $totalAmount,
            'paid_amount'        => 0, // initially 0 until gateway confirms
            'payment_status'     => 'unpaid',
            'currency'           => $package->currency ?? 'PKR',
            'notes'              => $request->notes,
            'status'             => 'pending',
        ]);

        // Auto-create document requirements
        foreach ($package->service->requirements as $req) {
            OrderDocument::create([
                'order_id'      => $order->id,
                'document_name' => $req->document_name,
                'status'        => 'pending',
                'is_required'   => $req->is_required,
            ]);
        }

        return redirect()->route('user.orders.show', $order)->with('success', "Order #{$order->order_number} initialized! Please proceed to document upload or payment.");
    }
}
