<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\OrderDetail;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $query = Order::with(['details', 'addons', 'payments', 'customer'])->latest();

        if ($request->has('status') && $request->status !== null) {
            $query->where('status', $request->status);
        }

        if ($request->has('search') && $request->search !== null) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('order_number', 'like', '%' . $search . '%')
                  ->orWhere('customer_name', 'like', '%' . $search . '%');
            });
        }

        $orders = $query->paginate(20);

        // Calculate payment status and totals for each order
        $orders->getCollection()->transform(function ($order) {
            $paidAmount = $order->payments->sum('received_amount');
            $totalAmount = $order->total;

            // Payment status calculation
            // 3 = Unpaid, 2 = Partially Paid, 1 = Fully Paid
            if ($paidAmount == 0) {
                $paymentStatus = 3;
            } elseif ($paidAmount < $totalAmount) {
                $paymentStatus = 2;
            } else {
                $paymentStatus = 1;
            }

            // Add calculated fields to response - CRITICAL: must use setAppends
            $order->setAttribute('paid_amount', $paidAmount);
            $order->setAttribute('payment_status', $paymentStatus);
            $order->setAttribute('due_amount', $totalAmount - $paidAmount);

            // Make sure these attributes are visible in JSON
            $order->makeVisible(['paid_amount', 'payment_status', 'due_amount']);

            return $order;
        });

        return response()->json([
            'success' => true,
            'data' => $orders
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string',
            'delivery_date' => 'required|date',
            'services' => 'required|array', // Array of service IDs and quantities
            'services.*.id' => 'required|exists:services,id',
            'services.*.quantity' => 'required|integer|min:1',
        ]);

        try {
            DB::beginTransaction();

            $order = new Order();
            $order->order_number = 'ORD-' . time(); // Simple generation, improve as needed
            $order->customer_name = $request->customer_name;
            $order->order_date = Carbon::now();
            $order->delivery_date = Carbon::parse($request->delivery_date);
            $order->status = 0; // Pending
            $order->created_by = Auth::id() ?? 1; // Default to admin if not auth
            
            // Calculate totals (simplified logic, should match backend more closely in real app)
            $sub_total = 0;
            $items = [];

            foreach ($request->services as $inputService) {
                $service = \App\Models\Service::find($inputService['id']);
                $price = $service->price; // Assume standard price
                $quantity = $inputService['quantity'];
                $total = $price * $quantity;
                $sub_total += $total;

                $items[] = [
                    'service_id' => $service->id,
                    'service_name' => $service->service_name,
                    'quantity' => $quantity,
                    'price' => $price,
                    'total' => $total
                ];
            }

            $order->sub_total = $sub_total;
            $order->discount = 0;
            $order->tax_amount = 0; // calculate if needed
            $order->algo_total = $order->sub_total; // Assuming final total
            $order->total = $order->sub_total;
            $order->save();

            // Save Details
            foreach ($items as $item) {
                OrderDetail::create([
                    'order_id' => $order->id,
                    'service_id' => $item['service_id'],
                    'service_name' => $item['service_name'],
                    'quantity' => $item['quantity'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Order created successfully',
                'data' => $order
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Failed to create order: ' . $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        try {
            $order = Order::with(['details', 'addons', 'payments', 'customer'])->find($id);

            if (!$order) {
                return response()->json([
                    'success' => false,
                    'message' => 'Order not found'
                ], 404);
            }

            // Calculate payment status and totals
            $paidAmount = $order->payments->sum('received_amount');
            $totalAmount = $order->total;

            // Payment status calculation
            // 3 = Unpaid, 2 = Partially Paid, 1 = Fully Paid
            if ($paidAmount == 0) {
                $paymentStatus = 3;
            } elseif ($paidAmount < $totalAmount) {
                $paymentStatus = 2;
            } else {
                $paymentStatus = 1;
            }

            // Add calculated fields to response
            $order->paid_amount = $paidAmount;
            $order->payment_status = $paymentStatus;
            $order->due_amount = $totalAmount - $paidAmount;

            return response()->json([
                'success' => true,
                'data' => $order
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error fetching order: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update order status
     */
    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|integer|min:0|max:4',
        ]);

        try {
            $order = Order::find($id);

            if (!$order) {
                return response()->json([
                    'success' => false,
                    'message' => 'Order not found'
                ], 404);
            }

            // Update status
            $order->status = $request->status;
            $order->save();

            return response()->json([
                'success' => true,
                'message' => 'Order status updated successfully',
                'data' => $order
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update order status: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete order
     */
    public function destroy($id)
    {
        try {
            $order = Order::find($id);

            if (!$order) {
                return response()->json([
                    'success' => false,
                    'message' => 'Order not found'
                ], 404);
            }

            DB::beginTransaction();

            // Delete related records
            OrderDetail::where('order_id', $order->id)->delete();
            \App\Models\OrderAddonDetail::where('order_id', $order->id)->delete();
            \App\Models\Payment::where('order_id', $order->id)->delete();

            // Delete order
            $order->delete();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Order deleted successfully'
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete order: ' . $e->getMessage()
            ], 500);
        }
    }
}
