<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\User;
use App\Models\OrderDetail;
use Illuminate\Pagination\LengthAwarePaginator;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;

class OrdersController extends Controller
{
   public function ordernew(){

    $neworder=Order::where('delivery_status','pending')->with('user')->paginate(10);
    return View('admin.partials.order.neworder', compact('neworder'));
 }

 public function order_all(){
   $allorder=Order::with('user')->paginate(10);
    return View('admin.partials.order.allorder', compact('allorder'));
 }

 public function orderdetail($id){
    $order = Order::with(['user', 'orderDetails.product'])->findOrFail($id);
    return View('admin.partials.order.orderDetail',compact('order'));
 }

public function confirm(Request $request, $id)
{
    $order = Order::findOrFail($id);

    $order->delivery_status = 'confirmed';
    $order->save();

    return back()->with('success', 'Order confirmed successfully');
}

public function cancel(Request $request, $id)
{
    $request->validate([
        'feedback' => 'required|string|max:500'
    ]);

    $order = Order::findOrFail($id);

    $order->delivery_status = 'cancelled';
    $order->admin_feedback = $request->feedback; // column in DB

    $order->save();

    return back()->with('success', 'Order cancelled successfully');
}


public function print($id)
{
    $order = Order::with(['user', 'orderDetails.product'])
        ->findOrFail($id);

    $qrText = "Order ID: {$order->id}\nTotal: {$order->grand_total}\nCustomer: " . ($order->shipping_address['name'] ?? '');

    $builder = new Builder(
        writer: new PngWriter(),
        data: $qrText,
        encoding: new Encoding('UTF-8'),
        errorCorrectionLevel: ErrorCorrectionLevel::High,
        size: 250,
        margin: 10
    );

    $result = $builder->build();

    $qrImage = $result->getDataUri();

    return view('admin.partials.order.printOrder', compact('order', 'qrImage'));
}


}
