<?php

namespace App\Http\Controllers;

use App\Models\UnlockOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class ShopOrderController extends Controller
{
    public function index()
    {
        $orders = Auth::guard('shop')->user()->unlockOrders()
            ->latest('date')
            ->get();

        return Inertia::render('Shop/Orders/Index', [
            'orders' => $orders,
        ]);
    }

    public function create()
    {
        $shopUser = Auth::guard('shop')->user();

        if (! $shopUser->canCreateOrder()) {
            return redirect()->route('shop.subscription.index')->with('error', 'Your plan has expired or you have reached the daily limit. Please upgrade your plan.');
        }

        return Inertia::render('Shop/Orders/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20',
            'device_model' => 'required|string|max:255',
            'imei_number' => 'required|string|max:20',
            'service_type' => 'required|in:frp,icloud,network,mdm',
            'note' => 'nullable|string',
            'service_price' => 'required|numeric|min:0',
        ]);

        UnlockOrder::create([
            'shop_user_id' => Auth::guard('shop')->id(),
            'customer_name' => $request->customer_name,
            'phone_number' => $request->phone_number,
            'device_model' => $request->device_model,
            'imei_number' => $request->imei_number,
            'service_type' => $request->service_type,
            'note' => $request->note,
            'service_price' => $request->service_price,
            'status' => 'pending',
            'date' => today(),
        ]);

        return redirect()->route('shop.orders.index')->with('success', 'Order submitted successfully!');
    }
}
