<?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\Credit;
use App\Models\Contact;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockDebtController extends Controller
{
    public function getStockOutDebtDue(Request $request)
    {

        $data = Stocktransaction::whereNotNull('cashin_id')
            ->whereNull('pending')
            ->whereRaw('paid < total')
            ->where(function ($query) {
                $query->whereNull('return_credit')
                    ->orWhere('return_credit', '<', 1);
            })
            ->with('contact', 'cashin', 'credit')
            ->orderBy('payment_due', 'ASC')->get();
        foreach ($data as $key => $value) {
            $day = date('Y-m-d', time());
            if ($value->payment_due > $day) {
                $value->payment_due = Carbon::create($value->payment_due)->diffForHumans(null, true) . " lagi";
            } else {
                $value->payment_due = Carbon::create($value->payment_due)->diffForHumans(null, true) . " yang lalu";
            }
        }

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

        ];

        return response($response, 200);
    }

    public function getStockOutDebt(Request $request)
    {
        $data = Stocktransaction::whereNotNull('cashin_id')
            ->whereNull('pending')
            ->where(function ($query) {
                $query->whereNull('return_credit')
                    ->orWhere('return_credit', '<', 1);
            });

        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->whereRaw('total > paid')->with('contact', 'cashin', 'credit')->orderBy('created_at', 'DESC')->get();

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

        ];

        return response($response, 200);
    }

    public function paidStockOut(Request $request)
    {
        $request->validate([
            'cashin_id' => 'required',
            'total' => 'required',
            'payment_due' => 'required',
            'staff' => 'required',
            'date' => 'required',
        ]);

        $stock = Stocktransaction::find($request->id);
        if (($stock->total + $stock->total_ppn - $stock->discount) < ($stock->paid + $request->total)) {
            return response(['error' => 'kelebihan dalam pembayaran'], 400);
        }
        $stock->paid = $stock->paid + $request->total;
        $stock->payment_due = date("Y-m-d", strtotime($request->payment_due));
        $stock->save();

        $akun = Akun::find($request->cashin_id);
        $akun->total = $akun->total + $request->total;
        $akun->save();

        $akun = Akun::where('name', '=', 'Piutang Penjualan')->first();
        $akun = Akun::find($akun->id);
        $akun->total = $akun->total - $request->total;
        $akun->save();

        $credit = new Credit;
        $credit->stocktransaction_id = $stock->id;
        $credit->cashin_id = $request->cashin_id;
        $credit->total = $request->total;
        $credit->staff = $request->staff;
        $credit->date = date("Y-m-d", strtotime($request->date));
        $credit->save();

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

        return response($response, 200);
    }

    public function paidStockIn(Request $request)
    {
        $request->validate([
            'cashout_id' => 'required',
            'total' => 'required',
            'payment_due' => 'required',
            'staff' => 'required',
            'date' => 'required',
        ]);

        $stock = Stocktransaction::find($request->id);
        if (($stock->total + $stock->total_ppn - $stock->discount) < ($stock->paid + $request->total)) {
            return response(['error' => 'kelebihan dalam pembayaran'], 400);
        }
        $stock->paid = $stock->paid + $request->total;
        $stock->payment_due = date("Y-m-d", strtotime($request->payment_due));
        $stock->save();

        $akun = Akun::find($request->cashout_id);
        $akun->total = $akun->total - $request->total;
        $akun->save();

        $akun = Akun::where('name', '=', 'Hutang Pembelian Non Tunai')->first();
        $akun = Akun::find($akun->id);
        $akun->total = $akun->total - $request->total;
        $akun->save();

        $credit = new Credit;
        $credit->stocktransaction_id = $stock->id;
        $credit->cashout_id = $request->cashout_id;
        $credit->total = $request->total;
        $credit->staff = $request->staff;
        $credit->date = date("Y-m-d", strtotime($request->date));
        $credit->save();

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

        return response($response, 200);
    }

    public function pphStockOut(Request $request)
    {
        $request->validate([
            'pph23_amount' => 'nullable',
            'pph22_amount' => 'nullable',
            'pph22_amount_v2' => 'nullable',
            'pph4_2_amount' => 'nullable',
            'pph4_2_amount_v2' => 'nullable',
            'pph21_amount' => 'nullable',
            'date' => 'required',
            'staff' => 'required',
        ]);

        DB::beginTransaction();
        try {
            $stock = Stocktransaction::find($request->id);
            if (!empty($request->pph23_amount)) {
                $stock->pph23_amount += $request->pph23_amount;
            } elseif (!empty($request->pph22_amount)) {
                $stock->pph22_amount += $request->pph22_amount;
            } elseif (!empty($request->pph22_amount_v2)) {
                $stock->pph22_amount_v2 += $request->pph22_amount_v2;
            } elseif (!empty($request->pph4_2_amount)) {
                $stock->pph4_2_amount += $request->pph4_2_amount;
            } elseif (!empty($request->pph4_2_amount_v2)) {
                $stock->pph4_2_amount_v2 += $request->pph4_2_amount_v2;
            } elseif (!empty($request->pph21_amount)) {
                $stock->pph21_amount += $request->pph21_amount;
            }
            $stock->save();

            $akunPPh23 = Akun::where('name', 'Piutang_PPh_Pasal_23')->first();
            $akunPPh22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
            $akunPPh4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
            $akunPPh21 = Akun::where('name', 'Piutang_PPh_21')->first();
            $akunUtangPPh4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();

            if (!empty($request->pph4_2_amount_v2)) {
                $credit = new Credit;
                $credit->stocktransaction_id = $stock->id;
                $credit->cashin_id = $akunPPh4_2->id;
                $credit->total = $request->pph4_2_amount_v2;
                $credit->staff = $request->staff;
                $credit->date = date("Y-m-d", strtotime($request->date));
                $credit->save();

                $credit = new Credit;
                $credit->stocktransaction_id = $stock->id;
                $credit->cashin_id = $akunUtangPPh4_2->id;
                $credit->total = $request->pph4_2_amount_v2;
                $credit->staff = $request->staff;
                $credit->date = date("Y-m-d", strtotime($request->date));
                $credit->save();
            } else {
                $credit = new Credit;
                $credit->stocktransaction_id = $stock->id;

                if (!empty($request->pph23_amount)) {
                    $credit->cashin_id = $akunPPh23->id;
                    $credit->total = $request->pph23_amount;
                } elseif (!empty($request->pph22_amount)) {
                    $credit->cashin_id = $akunPPh22->id;
                    $credit->total = $request->pph22_amount;
                } elseif (!empty($request->pph22_amount_v2)) {
                    $credit->cashin_id = $akunPPh22->id;
                    $credit->total = $request->pph22_amount_v2;
                } elseif (!empty($request->pph4_2_amount)) {
                    $credit->cashin_id = $akunPPh4_2->id;
                    $credit->total = $request->pph4_2_amount;
                } elseif (!empty($request->pph21_amount)) {
                    $credit->cashin_id = $akunPPh21->id;
                    $credit->total = $request->pph21_amount;
                }

                $credit->staff = $request->staff;
                $credit->date = date("Y-m-d", strtotime($request->date));
                $credit->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
        $response = [
            'success' => true,
            'stocktransaction' => $credit,
        ];

        return response($response, 200);
    }

    public function pphStockIn(Request $request)
    {
        $request->validate([
            'pph23_amount' => 'nullable',
            'pph22_amount' => 'nullable',
            'pph22_amount_v2' => 'nullable',
            'pph4_2_amount' => 'nullable',
            'pph21_amount' => 'nullable',
            'date' => 'required',
            'staff' => 'required',
        ]);

        DB::beginTransaction();
        try {
            $stock = Stocktransaction::find($request->id);
            if (!empty($request->pph23_amount)) {
                $stock->pph23_amount += $request->pph23_amount;
            } elseif (!empty($request->pph22_amount)) {
                $stock->pph22_amount += $request->pph22_amount;
            } elseif (!empty($request->pph22_amount_v2)) {
                $stock->pph22_amount_v2 += $request->pph22_amount_v2;
            } elseif (!empty($request->pph4_2_amount)) {
                $stock->pph4_2_amount += $request->pph4_2_amount;
            } elseif (!empty($request->pph21_amount)) {
                $stock->pph21_amount += $request->pph21_amount;
            }
            $stock->save();

            $akunPPh23 = Akun::where('name', 'Utang_PPh_23')->first();
            $akunPPh22 = Akun::where('name', 'Utang_PPh_22')->first();
            $akunPPh4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
            $akunPPh21 = Akun::where('name', 'Utang_PPh_21')->first();

            $credit = new Credit;
            $credit->stocktransaction_id = $stock->id;

            if (!empty($request->pph23_amount)) {
                $credit->cashout_id = $akunPPh23->id;
                $credit->total = $request->pph23_amount;
            } elseif (!empty($request->pph22_amount)) {
                $credit->cashout_id = $akunPPh22->id;
                $credit->total = $request->pph22_amount;
            } elseif (!empty($request->pph22_amount_v2)) {
                $credit->cashout_id = $akunPPh22->id;
                $credit->total = $request->pph22_amount_v2;
            } elseif (!empty($request->pph4_2_amount)) {
                $credit->cashout_id = $akunPPh4_2->id;
                $credit->total = $request->pph4_2_amount;
            } elseif (!empty($request->pph21_amount)) {
                $credit->cashout_id = $akunPPh21->id;
                $credit->total = $request->pph21_amount;
            }

            $credit->staff = $request->staff;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
        $response = [
            'success' => true,
            'stocktransaction' => $credit,
        ];

        return response($response, 200);
    }

    public function updateCreditTransaction(Request $request)
    {
        $request->validate([
            'cashout_id' => 'nullable',
            'cashin_id' => 'nullable',
            'total' => 'required',
            'staff' => 'required',
            'date' => 'required',
        ]);

        $akunPPh23 = Akun::where('name', 'Piutang_PPh_Pasal_23')->first();
        $akunPPh22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $akunPPh4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
        $akunPPh21 = Akun::where('name', 'Piutang_PPh_21')->first();

        $akunUtangPPh23 = Akun::where('name', 'Utang_PPh_23')->first();
        $akunUtangPPh22 = Akun::where('name', 'Utang_PPh_22')->first();
        $akunUtangPPh4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $akunUtangPPh21 = Akun::where('name', 'Utang_PPh_21')->first();

        $credit = Credit::find($request->id);
        $stock = Stocktransaction::find($credit->stocktransaction_id);

        if ($credit->cashin_id == $akunPPh23->id) {
            $stock->pph23_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph23_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashin_id == $akunPPh22->id) {
            $stock->pph22_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph22_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashin_id == $akunPPh4_2->id) {
            $stock->pph4_2_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph4_2_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashin_id == $akunPPh21->id) {
            $stock->pph21_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph21_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashout_id == $akunUtangPPh23->id) {
            $stock->pph23_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph23_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashout_id == $akunUtangPPh22->id) {
            $stock->pph22_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph22_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashout_id == $akunUtangPPh4_2->id) {
            $stock->pph4_2_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph4_2_amount += $credit->total;
            $stock->save();
        } elseif ($credit->cashout_id == $akunUtangPPh21->id) {
            $stock->pph21_amount -= $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->pph21_amount += $credit->total;
            $stock->save();
        } else {
            $stock->paid = $stock->paid - $credit->total;
            $stock->save();

            $credit->total = $request->total;
            $credit->cashin_id = $request->cashin_id;
            $credit->cashout_id = $request->cashout_id;
            $credit->date = date("Y-m-d", strtotime($request->date));
            $credit->save();

            $stock->paid = $stock->paid + $credit->total;
            $stock->save();
        }

        $response = [
            'success' => true,
            'cresirt' => $credit,
        ];

        return response($response, 200);
    }

    public function deleteCreditTransaction(Request $request)
    {

        $credit = Credit::find($request->id);
        $stock = Stocktransaction::find($credit->stocktransaction_id);

        if ($stock->cashin_id) { // Penjualan
            $akunPPh23 = Akun::where('name', 'Piutang_PPh_Pasal_23')->first();
            $akunPPh22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
            $akunPPh4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
            $akunPPh4_2_v2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
            $akunPPh21 = Akun::where('name', 'Piutang_PPh_21')->first();

            if ($credit->cashin_id == $akunPPh23->id) {
                $stock->pph23_amount -= $credit->total;
                $stock->save();
            } elseif ($credit->cashin_id == $akunPPh22->id) {
                $stock->pph22_amount -= $credit->total;
                $stock->save();
            } elseif ($credit->cashin_id == $akunPPh4_2->id) {
                if ($stock->pph4_2_amount_v2 < 1) {
                    $stock->pph4_2_amount -= $credit->total;
                    $stock->save();
                }
            } elseif ($credit->cashin_id == $akunPPh4_2_v2->id) {
                $stock->pph4_2_amount_v2 -= $credit->total;
                $stock->save();
            } elseif ($credit->cashin_id == $akunPPh21->id) {
                $stock->pph21_amount -= $credit->total;
                $stock->save();
            } else {
                $stock = Stocktransaction::find($stock->id);
                $stock->paid = $stock->paid - $credit->total;
                $stock->save();

                $akun = Akun::where('name', '=', 'Piutang Penjualan')->first();
                $akun = Akun::find($akun->id);
                $akun->total = $akun->total + $credit->total;
                $akun->save();
            }
        } elseif ($stock->cashout_id) { // Pembelian

            $akunUtangPPh23 = Akun::where('name', 'Utang_PPh_23')->first();
            $akunUtangPPh22 = Akun::where('name', 'Utang_PPh_22')->first();
            $akunUtangPPh4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
            $akunUtangPPh21 = Akun::where('name', 'Utang_PPh_21')->first();

            if ($credit->cashout_id == $akunUtangPPh23->id) {
                $stock->pph23_amount -= $credit->total;
                $stock->save();
            } elseif ($credit->cashout_id == $akunUtangPPh22->id) {
                $stock->pph22_amount -= $credit->total;
                $stock->save();
            } elseif ($credit->cashout_id == $akunUtangPPh4_2->id) {
                $stock->pph4_2_amount -= $credit->total;
                $stock->save();
            } elseif ($credit->cashout_id == $akunUtangPPh21->id) {
                $stock->pph21_amount -= $credit->total;
                $stock->save();
            } else {
                $stock = Stocktransaction::find($stock->id);
                $stock->paid = $stock->paid - $credit->total;
                $stock->save();

                $akun = Akun::where('name', '=', 'Hutang Pembelian Non Tunai')->first();
                $akun = Akun::find($akun->id);
                $akun->total = $akun->total + $credit->total;
                $akun->save();
            }
        }

        $credit->delete();

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

        return response($response, 200);
    }
}
