<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Stocktransaction;
use App\Models\Substocktransaction;
use App\Models\Product;
use App\Models\Akun;
use App\Models\Cashtransaction;
use App\Models\Credit;
use App\Models\Contact;
use App\Models\Subcashtransaction;
use Illuminate\Support\Facades\DB;

class StockNonMoneyController extends Controller
{

    public function getStockIn(Request $request)
    {

        $data = Stocktransaction::where('nonmoney', 'in', 'contact')->where('is_so', false);

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $request->start_date = date('Y-m-d', strtotime($request->start_date));
            $request->end_date = date('Y-m-d', strtotime($request->end_date));
            $data = $data->whereBetween('date', [$request->start_date, $request->end_date]);
        }
        // else{
        //     $data = $data->whereBetween('date',[date('Y-m-01',time()),date('Y-m-d',time())]);
        // }
        if ($request->type) {
            $data = $data->where('type', $request->type);
        } else {
            $data = $data->whereNull('type');
        }
        $data = $data->with('substocktransaction.product.unit', 'contact')->orderByDesc('id')->get();

        $response = [
            'success' => true,
            'stocktransaction' => $data,
        ];

        return response($response, 200);
    }

    public function getStockOut(Request $request)
    {
        $data = Stocktransaction::where('nonmoney', 'out', 'contact')->where('is_so', false)->whereNull('production_id');

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $request->start_date = date('Y-m-d', strtotime($request->start_date));
            $request->end_date = date('Y-m-d', strtotime($request->end_date));
            $data = $data->whereBetween('date', [$request->start_date, $request->end_date]);
        }
        // else{
        //     $data = $data->whereBetween('date',[date('Y-m-01',time()),date('Y-m-d',time())]);
        // }

        $data = $data->with('substocktransaction.product.unit', 'contact')->orderByDesc('id')->get();

        $response = [
            'success' => true,
            'stocktransaction' => $data,
        ];

        return response($response, 200);
    }

    public function getStockTransactionDetail(Request $request)
    {
        $data = Stocktransaction::where('id', $request->id)->with('contact', 'substocktransaction', 'substocktransaction.product')->get();

        $response = [
            'success' => true,
            'stocktransaction' => $data,

        ];

        return response($response, 200);
    }

    public function createStockIn(Request $request)
    {
        $request->validate([
            'staff' => 'required',
            'date' => 'required',
            'contact_id' => 'nullable',
            'product_id.*' => 'required',
            'qty.*'  => 'required',
            'purchase_price.*'  => 'required',
            'total.*'  => 'required|numeric',
        ]);

        // Mulai database transaction
        DB::beginTransaction();

        try {
            $stock = new Stocktransaction;
            $stock->staff = $request->staff;
            $stock->date = date("Y-m-d", strtotime($request->date));
            $stock->type = $request->type;
            $stock->description = $request->desc;
            $stock->nonmoney = 'in';
            $stock->contact_id = $request->contact_id;
            $stock->save();

            if (empty($request->type)) {
                $cash = new Cashtransaction;
                $cash->staff = $request->staff;
                $cash->date = date("Y-m-d", strtotime($request->date));
                $cash->transaction_category = 'pendapatan_item_masuk';
                $cash->contact_id = $request->contact_id;
                $cash->stocktransaction_id = $stock->id;
                $cash->cashout = 0;
                $cash->cashin = 0;
                $cash->transfer = 0;
                $cash->save();

                $stock->cashtransaction_id = $cash->id;
                $stock->save();
            }

            $data = $request->product_id;
            $total = 0;
            $substocktransaction = [];

            foreach ($data as $key => $value) {
                $sub = new Substocktransaction;
                $sub->stocktransaction_id = $stock->id;
                $sub->product_id = $request->product_id[$key];
                $sub->qty = $request->qty[$key];
                $sub->purchase_price = $request->purchase_price[$key];
                $sub->left = $request->qty[$key];
                $sub->total = $request->total[$key];
                $sub->save();

                $substocktransaction[] = $sub;

                $product = Product::find($sub->product_id);
                $product->qty = $product->qty + $sub->qty;
                $product->save();

                $total = $total + $request->total[$key];
            }

            $akun = Akun::where('name', '=', 'Persediaan Barang')->first();
            $akun = Akun::find($akun->id);
            $akun->total = $akun->total + $total;
            $akun->save();

            $akun = Akun::where('name', '=', 'Pendapatan Barang')->first();
            $akun = Akun::find($akun->id);
            $akun->total = $akun->total + $total;
            $akun->save();

            $stock = Stocktransaction::find($stock->id);
            $stock->total = $total;
            $stock->save();

            if (empty($request->type)) {
                $sub = new Subcashtransaction;
                $sub->cashtransaction_id = $cash->id;
                $sub->akun_id = 43;
                $sub->total = $total;
                $sub->desc = $request->desc;
                $sub->save();
            }

            // Commit transaction jika semua berhasil
            DB::commit();

            $response = [
                'success' => true,
                'stockktransaction' => $stock,
                'substocktransaction' => $substocktransaction,
            ];

            return response($response, 200);
        } catch (\Exception $e) {
            // Rollback transaction jika terjadi error
            DB::rollback();

            return response()->json([
                'status' => 'error',
                'message' => 'Terjadi kesalahan saat memproses data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function createStockOut(Request $request)
    {
        $request->validate([
            'staff' => 'required',
            'date' => 'required',
            'contact_id' => 'nullable',
            'product_id.*' => 'required',
            'qty.*'  => 'required',
        ]);

        // Mulai database transaction
        DB::beginTransaction();

        try {
            $contact = Contact::where('id', $request->contact_id)->first();
            $sum = 0;

            $data = $request->product_id;
            // Pengecekan stok produk
            foreach ($data as $key => $value) {
                $dataQty = $request->qty[$key];
                $dataProduct = Product::find($request->product_id[$key]);

                if ($dataQty > $dataProduct->qty) {
                    // Rollback transaction jika stok tidak mencukupi
                    DB::rollback();
                    return response()->json([
                        'status' => 'error',
                        'error' => 'Stok tidak mencukupi untuk produk: ' . $dataProduct->name . '. Stok tersedia: ' . $dataProduct->qty
                    ], 400);
                }
            }

            $stock = new Stocktransaction;
            $stock->staff = $request->staff;
            $stock->description = $request->desc;
            $stock->date = date("Y-m-d", strtotime($request->date));
            $stock->nonmoney = 'out';
            $stock->contact_id = $request->contact_id;
            $stock->save();

            $cash = new Cashtransaction;
            $cash->staff = $request->staff;
            $cash->date = date("Y-m-d", strtotime($request->date));
            $cash->transaction_category = 'biaya_item_keluar';
            $cash->contact_id = $request->contact_id;
            $cash->stocktransaction_id = $stock->id;
            $cash->cashout = 0;
            $cash->cashin = 0;
            $cash->transfer = 0;
            $cash->save();

            $stock->cashtransaction_id = $cash->id;
            $stock->save();

            $total = 0;
            $totalhpp = 0;
            $lasthb = 0;
            $substocktransaction = [];

            foreach ($data as $key => $value) {
                $sub = new Substocktransaction;
                $sub->stocktransaction_id = $stock->id;
                $sub->product_id = $request->product_id[$key];
                $sub->qty = $request->qty[$key];
                $sub->save();

                $substocktransaction[] = $sub;

                $product = Product::find($sub->product_id);
                $product->qty = $product->qty - $sub->qty;
                $product->save();

                $qty = $sub->qty;
                $substocktransactions_ids = [];
                $subin = Substocktransaction::where('left', '>', 0)
                    ->whereHas('stocktransaction', function ($query) {
                        $query->whereNull('pending');
                    })
                    ->where('product_id', '=', $sub->product_id)
                    ->get();

                foreach ($subin as $key => $value) {
                    array_push($substocktransactions_ids, $value->id);

                    if ($qty <= $value->left) {

                        $set = $value->left - $qty;

                        $sibin = Substocktransaction::find($value->id);
                        $sibin->left = $set;
                        $sibin->save();

                        $totalhpp = $totalhpp + ($value->purchase_price * $qty);
                        break;
                    } else {
                        $set = 0;
                        $qty = $qty - $value->left;
                        $totalhpp = $totalhpp + ($value->purchase_price * $value->left);

                        $sibin = Substocktransaction::find($value->id);
                        $sibin->left = $set;
                        $sibin->save();
                    }

                    $lasthb = $value->purchase_price;
                }
                $sibin = Substocktransaction::find($sub->id);
                $sibin->hpp = $totalhpp;
                $sibin->substocktransactions_ids = join(",", $substocktransactions_ids);
                $sibin->save();
                $totalhpp = 0;
                $total = $total + $sub->total;
            }

            if ($qty > 0) {
                $totalhpp = $totalhpp + ($lasthb * $qty);
            }

            $akun = Akun::where('name', '=', 'Persediaan Barang')->first();
            $akun = Akun::find($akun->id);
            $akun->total = $akun->total - $totalhpp;
            $akun->save();

            $akun = Akun::where('name', '=', 'Kerugian Barang Keluar Tanpa Penjualan')->first();
            $akun = Akun::find($akun->id);
            $akun->total = $akun->total + $totalhpp;
            $akun->save();

            $stock = Stocktransaction::find($stock->id);
            $stock->total = $total;
            $stock->save();

            $sub = new Subcashtransaction;
            $sub->cashtransaction_id = $cash->id;
            $sub->akun_id = 31;
            $sub->total = $sibin->hpp;
            $sub->desc = $request->desc;
            $sub->save();

            // Commit transaction jika semua berhasil
            DB::commit();

            $response = [
                'success' => true,
                'stockktransaction' => $stock,
                'substocktransaction' => $substocktransaction,
            ];
            return response($response, 200);
        } catch (\Exception $e) {
            // Rollback transaction jika terjadi error
            DB::rollback();

            return response()->json([
                'status' => 'error',
                'message' => 'Terjadi kesalahan saat memproses data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function deleteStockTransaction(Request $request)
    {
        // data yang ingin di hapus
        $stock = Stocktransaction::with('substocktransaction')
            ->find($request->id);

        if ($stock) {
            // mengambil semua transaksi pembelian sebelumnya
            // $out = Stocktransaction::where('id', $stock->id)
            //                ->with('substocktransaction')
            //                ->get()
            //                ->map(function ($item){
            //                  $substocktransaction = $item->substocktransaction;
            //                  return $substocktransaction->map(function ($item2) {
            //                      return Substocktransaction::where('substocktransactions_ids', 'LIKE', '%' . $item2->id . '%')->first();
            //                  });
            //                });
            //  $out = $out[0][0];
            $out = Stocktransaction::where('id', $stock->id)
                ->with('substocktransaction')
                ->get()
                ->map(function ($item) {
                    $substocktransaction = $item->substocktransaction;
                    return $substocktransaction->flatMap(function ($item2) {
                        return Substocktransaction::where('substocktransactions_ids', 'LIKE', '%' . $item2->id . '%')->get();
                    });
                })
                ->flatten();

            $out = $out->first();

            if ($stock->nonmoney == "out") {
                $sub = Substocktransaction::where('stocktransaction_id', '=', $stock->id)->get();
                $totalhpp = 0;
                foreach ($sub as $key => $value) {
                    $product = Product::find($value->product_id);
                    $product->qty = $product->qty + $value->qty;
                    $product->save();

                    $totalhpp = $totalhpp + $value->hpp;
                    $qty = $value->qty;
                    $subin = Substocktransaction::whereNotNull('purchase_price')->where('product_id', '=', $product->id)->orderBy('id', 'desc')->get();
                    foreach ($subin as $key => $value) {

                        if ($qty <= $value->qty) {

                            $set = $value->left + $qty;

                            $sibin = Substocktransaction::find($value->id);
                            $sibin->left = $set;
                            $sibin->save();
                            break;
                        } else {
                            $set = $value->qty;
                            $qty = $qty - $value->qty;

                            $sibin = Substocktransaction::find($value->id);
                            $sibin->left = $set;
                            $sibin->save();
                        }
                    }
                }

                $akun = Akun::where('name', '=', 'Persediaan Barang')->first();
                $akun = Akun::find($akun->id);
                $akun->total = $akun->total + $totalhpp;
                $akun->save();

                $akun = Akun::where('name', '=', 'Kerugian Barang Keluar Tanpa Penjualan')->first();
                $akun = Akun::find($akun->id);
                $akun->total = $akun->total - $totalhpp;
                $akun->save();

                // menghapus cashtransaction
                $data = Cashtransaction::find($stock->cashtransaction_id);
                if ($data) {
                    if ($data->transaction_category === 'biaya_item_keluar') {
                        Subcashtransaction::where('cashtransaction_id', $stock->cashtransaction_id)->delete();
                    }

                    $data->delete();
                }

                Substocktransaction::where('stocktransaction_id', '=', $stock->id)->delete();
                $stock->delete();

                $response = [
                    'success' => true,
                    'stocktransaction' => $stock,
                ];
                return response($response, 200);
            } elseif ($stock->nonmoney == "in") {

                if (!$out) {
                    $totalhpp = 0;
                    $sub = Substocktransaction::where('stocktransaction_id', '=', $stock->id)->get();
                    foreach ($sub as $key => $value) {
                        $product = Product::find($value->product_id);
                        $product->qty = $product->qty - $value->qty;
                        $product->save();

                        $totalhpp = $totalhpp + ($value->left * $value->purchase_price);
                    }

                    $akun = Akun::where('name', '=', 'Persediaan Barang')->first();
                    $akun = Akun::find($akun->id);
                    $akun->total = $akun->total - $stock->total;
                    $akun->save();

                    $akun = Akun::where('name', '=', 'Pendapatan Barang')->first();
                    $akun = Akun::find($akun->id);
                    $akun->total = $akun->total - $stock->total;
                    $akun->save();

                    // menghapus cashtransaction
                    $data = Cashtransaction::find($stock->cashtransaction_id);
                    if ($data) {
                        if ($data->transaction_category === 'pendapatan_item_masuk') {
                            Subcashtransaction::where('cashtransaction_id', $stock->cashtransaction_id)->delete();
                        }

                        $data->delete();
                    }

                    Substocktransaction::where('stocktransaction_id', '=', $stock->id)->delete();
                    $stock->delete();

                    $response = [
                        'success' => true,
                        'stocktransaction' => $stock,
                    ];
                    return response($response, 200);
                } else {
                    $response = [
                        'success' => false,
                        'message' => 'Produk dalam transaksi ini telah dikeluarkan dalam PENJUALAN / KOREKSI STOK - KURANGI STOK dengan nomor transaksi: ' . $out->stocktransaction_id . '. Jika Anda ingin menghapus transaksi ini, silakan hapus transaksi tersebut terlebih dahulu.',
                    ];
                    return response($response, 400);
                }
            }
        } else {
            $response = [
                'success' => false,
                'message' => 'not found'
            ];
            return response($response, 400);
        }
    }
}
