<?php

namespace App\Http\Controllers\Evo;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\OrderHistory;
use App\Models\AppOrder;
use App\Models\AppOrderItem;
use Illuminate\Support\Facades\DB;

class OrderHistoryController extends Controller
{
    public function uploadBulkData(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'xml_file' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'message' => 'Validation Error',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {

            // Truncate the orderhistory table before inserting new data
            OrderHistory::truncate();


            $xml = simplexml_load_file($request->file('xml_file')->getRealPath());

            $data = [];
            foreach ($xml->children() as $order) {
                $data = [
                    'CustomerNo' => (string) $order->CustomerNo,
                    'ProductCode' => (string) $order->ProductCode,
                    'Sunday' => (int) $order->Sunday,
                    'Monday' => (int) $order->Monday,
                    'Tuesday' => (int) $order->Tuesday,
                    'Wednesday' => (int) $order->Wednesday,
                    'Thursday' => (int) $order->Thursday,
                    'Friday' => (int) $order->Friday,
                    'Saturday' => (int) $order->Saturday,
                    'Total' => (int) $order->Total,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];

                OrderHistory::insert($data);
            }



            return response()->json([
                'status' => true,
                'message' => 'Bulk data uploaded successfully!'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['status' => false, 'message' => 'Something went wrong with the file.'], 404);
        }
    }


    public function getAllUnprocessedOrders()
    {

        $unprocessedOrders = DB::table('app_orders')
            ->select('app_orders.id', 'app_orders.CustomerNo', 'app_orders.CreatedBy', 'app_orders.DeliveryDate', 'app_orders.ProcessStatus', 'app_orders.created_at', 'app_order_items.ProductCode', 'app_order_items.Quantity')
            ->join('app_order_items', 'app_orders.id', '=', 'app_order_items.app_order_id')
            ->where('app_orders.ProcessStatus', 'Pending')
            ->get();


        return response()->json(['status' => true, 'data' => $unprocessedOrders], 200);
    }
}
