<?php

namespace App\Service\Order;

use App\Models\OrderDetail;
use App\Models\OrderMaster;
use App\Models\SalesDetails;
use App\Models\SalesMaster;
use App\Models\WarehouseStock;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OrderService
{
    public static function store(array $data)
    {

        DB::transaction(function () use ($data) {
            $collection = collect($data);

            // Calculate the first discount amount
            if (isset($collection['discount_first'])) {
                $firstDiscountAmount = $collection['total'] * (isset($collection['discount_first']) ? $collection['discount_first'] : 0) / 100;
                // Calculate the total after applying the first discount
                $totalAfterFirstDiscount = $collection['total'] - $firstDiscountAmount;
                // Calculate the second discount amount based on the amount after the first discount
            } else {
                $firstDiscountAmount = 0;
                $totalAfterFirstDiscount = 0;
            }
            if (isset($collection['discount_second'])) {
                $secondDiscountAmount = $totalAfterFirstDiscount * (isset($collection['discount_second']) ? $collection['discount_second'] : 0) / 100;
            } else {
                $secondDiscountAmount = 0;
            }

            // Total discount amount
            $totalDiscount = $firstDiscountAmount + $secondDiscountAmount;

            $order = OrderMaster::orderby('id', 'DESC')->first();
            $reference = '00001';
            if ($order) {
                $next_number = sprintf('%05d', (int) $order->order_no + 1);
                $reference = $next_number;
            }

            $order = OrderMaster::create([
                'date' => $collection['date'],
                'order_no' => $reference,
                'supplier_id' => Auth::user()->supplier_id,
                'user_id' => Auth::user()->id,
                'client_id' => isset($collection['costomer_id']) ? $collection['costomer_id'] : null,
                'total' => $collection['total'],
                'discount_first' => isset($collection['discount_first']) ? $collection['discount_first'] : 0,
                'discount_second' => isset($collection['discount_second']) ? $collection['discount_second'] : 0,
                'total_discount' => $totalDiscount,
                'status' => 1,
                'grand_total' => $collection['grand_total'],
                'note' => isset($collection['note']) ? $collection['note'] : '',
            ]);

            foreach (isset($collection['list']) ? $collection['list'] : [] as $key => $value) {
                OrderDetail::create([
                    'order_master_id' => $order->id,
                    'product_id' => $value['product_id'],
                    'attribute_id' => $value['attribute_id'],
                    'quantity' => $value['quantity'],
                    'gift' => isset($value['gift']) && ($value['gift'] !== null) ? $value['gift'] : 0,

                    'price' => $value['price'],
                    'discount' => isset($value['discount']) ? $value['discount'] : 0,
                    'total_discount' => isset($value['discount']) ? $value['discount'] : 0,
                    'total' => $value['total'],

                ]);
            }
        });
    }

    public static function update(array $data, $id)
    {
        DB::transaction(function () use ($data, $id) {

            $collection = collect($data);

            // Calculate the first discount amount
            if (isset($collection['discount_first'])) {
                $firstDiscountAmount = $collection['total'] * (isset($collection['discount_first']) ? $collection['discount_first'] : 0) / 100;
                // Calculate the total after applying the first discount
                $totalAfterFirstDiscount = $collection['total'] - $firstDiscountAmount;
                // Calculate the second discount amount based on the amount after the first discount
            } else {
                $firstDiscountAmount = 0;
                $totalAfterFirstDiscount = 0;
            }
            if (isset($collection['discount_second'])) {
                $secondDiscountAmount = $totalAfterFirstDiscount * (isset($collection['discount_second']) ? $collection['discount_second'] : 0) / 100;
            } else {
                $secondDiscountAmount = 0;
            }
            $totalDiscount = $firstDiscountAmount + $secondDiscountAmount;

            $order = OrderMaster::orderby('id', 'DESC')->first();
            $reference = '00001';
            if ($order) {
                $next_number = sprintf('%05d', (int) $order->order_no + 1);
                $reference = $next_number;
            }

            $order = OrderMaster::where('id', $id)->update([
                'date' => $collection['date'],
                'supplier_id' => Auth::user()->supplier_id,
                'user_id' => Auth::user()->id,
                'client_id' => isset($collection['costomer_id']) ? $collection['costomer_id'] : null,
                'total' => $collection['total'],
                'discount_first' => isset($collection['discount_first']) ? $collection['discount_first'] : 0,
                'discount_second' => isset($collection['discount_second']) ? $collection['discount_second'] : 0,
                'total_discount' => $totalDiscount,
                'status' => 1,
                'grand_total' => $collection['grand_total'],
                'note' => isset($collection['note']) ? $collection['note'] : '',
            ]);

            OrderDetail::where('order_master_id', $id)->delete();
            foreach (isset($collection['list']) ? $collection['list'] : [] as $key => $value) {
                OrderDetail::create([
                    'order_master_id' => $id,
                    'product_id' => $value['product_id'],
                    'attribute_id' => $value['attribute_id'],
                    'quantity' => $value['quantity'],
                    'gift' => isset($value['gift']) && ($value['gift'] !== null) ? $value['gift'] : 0,

                    'price' => $value['price'],
                    'discount' => isset($value['discount']) ? $value['discount'] : 0,
                    'total_discount' => isset($value['discount']) ? $value['discount'] : 0,
                    'total' => $value['total'],

                ]);
            }
        });
    }

    public static function generateInvoiceNumber()
    {
        $prefix = 'S';
        $year = date('y'); // Two-digit year
        $month = date('m'); // Two-digit month
        $day = date('d'); // Two-digit day
        $randomNumber = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT); // 6-digit random number
        // Combine all parts into the final invoice number
        $invoiceNumber = "{$prefix}{$year}{$month}{$day}{$randomNumber}";

        return $invoiceNumber;
    }

    public static function sealsStore($data, $id)
    {

        DB::transaction(function () use ($data, $id) {

            $collection = collect($data);

            // Calculate the first discount amount
            if ((int) $collection['discount_first'] != 0) {
                $firstDiscountAmount = $collection['total'] * (isset($collection['discount_first']) ? $collection['discount_first'] : 0) / 100;
                // Calculate the total after applying the first discount
                $totalAfterFirstDiscount = $collection['total'] - $firstDiscountAmount;
                // Calculate the second discount amount based on the amount after the first discount
            } else {
                $firstDiscountAmount = 0;
                $totalAfterFirstDiscount = 0;
            }
            if ((int) $collection['discount_second'] != 0) {
                $secondDiscountAmount = $totalAfterFirstDiscount * (isset($collection['discount_second']) ? $collection['discount_second'] : 0) / 100;
            } else {
                $secondDiscountAmount = 0;
            }

            // Total discount amount
            $totalDiscount = $firstDiscountAmount + $secondDiscountAmount;

            $for_master = $collection->only('discount', 'after_vat', 'after_discount', 'total', 'grand_total', 'discount_second');
            $prepare_master = $for_master->merge([
                'invoice_no' => self::generateInvoiceNumber(),
                'user_id' => Auth::user()->id,
                'order_id' => $collection['order_id'],
                'transfer_type' => 'cash',
                'client_id' => $collection['costomer_id'],
                'sr_id' => $collection['sr_id'],
                'invoice_type' => 'TP',
                'supplier_id' => $collection['supplier_id'],
                'created_at' => Carbon::parse($collection['date'])->addDay(),
                'discount' => isset($collection['discount_first']) ? $collection['discount_first'] : 0,
                'after_discount' => $collection['discount_first'] == 0 || $collection['discount_second'] == 0 ? $totalDiscount : 0,
                'total' => $collection['total'],
                'grand_total' => $collection['grand_total'],

                'discount_second' => isset($collection['discount_second']) ? $collection['discount_second'] : 0,

            ]);
            $master = SalesMaster::create($prepare_master->toArray());

            $status = 0;
            foreach (isset($collection['list']) ? $collection['list'] : [] as $key => $value) {
                if ($value['quantity'] != 0) {

                    SalesDetails::create([
                        'sales_masters_id' => $master->id,
                        'order_details_id' => $value['order_details_id'],
                        'created_at' => Carbon::parse($collection['date'])->addDay(),
                        'product_id' => $value['product_id'],
                        'attribute_id' => $value['attribute_id'],
                        'qty' => $value['quantity'],
                        // 'gift' => isset($value['gift']) && ($value['gift'] !== null) ? $value['gift'] : 0,
                        'discount' => isset($value['discount']) ? $value['discount'] : 0,
                        'after_discount' => $value['total'] - $value['discount'],
                        'discount_type' => 'flat',
                        'price' => $value['price'],
                        'total' => $value['total'],
                    ]);
                    WarehouseStock::where('attribute_id', $value['attribute_id'])->where('supplier_id', $collection['supplier_id'])->update([
                        'quantity' => DB::raw('quantity - '.$value['quantity']),
                    ]);
                    if ($value['need_qty'] <= $value['quantity'] + (int) $value['seal_qty']) {
                        $status = 0;
                    } else {
                        $status = 1;
                    }
                }
            }
            foreach (isset($collection['list']) ? $collection['list'] : [] as $key => $value) {
                if ((int) $value['need_qty'] <= (int) $value['quantity'] + (int) $value['seal_qty']) {
                    $status = 0;
                } else {
                    $status = 1;
                    break;
                }
            }

            if ($status == 0) {
                OrderMaster::where('id', $id)->update(['status' => 2]);
            } else {
                OrderMaster::where('id', $id)->update(['status' => 3]);
            }
        });
    }
}
