<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Order;
use App\Services\LogTracker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class SteadFastWebhookController extends Controller
{
  public function handle(Request $request)
  {

    $expectedToken = 'Bearer ' . 'a13da2018d51';
    $authHeader = $request->header('Authorization');

    if ($authHeader !== $expectedToken) {
      Log::warning('Unauthorized Steadfast webhook attempt', ['header' => $authHeader]);
      return response()->json([
        'status' => 'error',
        'message' => 'Unauthorized request.'
      ], 401);
    }

    $data = $request->all();
    Log::info('Valid webhook received', $data);

    $merchantOrderId = $data['invoice'] ?? null;
    $orderStatus = $data['status'] ?? null;

    Log::info('steadfast Order Status: ' . ($orderStatus ?: 'N/A'));

    // Find order
    $order = Order::where('invoice_no', $merchantOrderId)->first();

    if ($order && $orderStatus) {

      if ($orderStatus === 'delivered') {
        $order->status = 5; // Delivered
        $order->delivery_date = Carbon::now();
      } else if ($orderStatus === 'cancelled') {
        $order->status = 11; // Returned
        $order->return_date = Carbon::now();
      } else if ($orderStatus === 'partial_delivered') {
        $order->status = 10;
      }

      if ($order->isDirty('status')) {
        $order->save();
      }
    }

    return response()->json([
      'status' => 'success',
      'message' => 'Webhook received successfully.',
    ], 200);
  }
}
