<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\CustomOrder;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AccountController extends Controller
{
    /**
     * Show user account page
     */
    public function show(): View
    {
        return view('account.profile', [
            'user' => auth()->user(),
        ]);
    }

    /**
     * Update user account
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . auth()->id(),
        ]);

        auth()->user()->update($validated);

        return redirect()->route('my-account')->with('success', 'Profile updated successfully.');
    }

    /**
     * Show user's orders (both standard and custom)
     */
    public function orders(): View
    {
        $user = auth()->user();

        $standardOrders = Order::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->get();

        $customOrders = CustomOrder::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->get();

        return view('account.orders', [
            'standardOrders' => $standardOrders,
            'customOrders' => $customOrders,
        ]);
    }

    /**
     * Show order detail (both standard and custom)
     */
    public function orderDetail(Order $order)
    {
        // Check authorization
        if ($order->user_id !== auth()->id() && !auth()->user()->is_admin) {
            abort(403);
        }

        return view('account.order-detail', [
            'order' => $order,
        ]);
    }

}