<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\ActualPayment;
use App\Models\BankAccount;
use App\Models\BankTransaction;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Product;
use App\Models\ReturnItem;
use App\Models\ReturnTbl;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ReturnSaleController extends Controller
{
    public function index(Request $request)
    {   
        $data['returns'] = ReturnTbl::orderBy('created_at','desc')->paginate(20);
        $data['customers'] =Customer::orderBy('name', 'DESC')->get();
        $data['customer_id'] = $request->customer_id;
        $data['startDate'] = $request->startDate;
        $data['endDate'] = $request->endDate;
        $sdate = Carbon::createFromDate($request->startDate)->toDateString();
        $edate = Carbon::createFromDate($request->endDate)->toDateString();
        // dd($sdate,$edate);
        if ($request->customer_id != NULL) {
            $returnItem = ReturnTbl::where('customer_id',$request->customer_id)
            ->orderBy('created_at', 'DESC');
            $data['returns'] = $returnItem->get();
        }

        if ($request->startDate != NULL && $request->endDate != NULL) {
            $returnItem = ReturnTbl::whereBetween('date', [$sdate, $edate])->orderBy('created_at', 'DESC');
            $data['returns'] = $returnItem->get();
        }
        return view('backend.pages.return.sale.index',$data);
    }

    public function create($id)
    {
        if (Invoice::where('status', 2)->where('id', $id)->first()) {
            notify()->warning('Product already returned');
            return redirect()->back();
        } else {
            $data['invoice'] = Invoice::where('id', $id)->first();
            $data['bank_accounts'] = BankAccount::where('status', 1)->get();
            return view('backend.pages.return.sale.create', $data);
        }
    }


    public function insert(Request $request)
    {

        $total_due = Invoice::where('id',$request->invoice_id)->first();
        $total_paid = Invoice::where('id',$request->invoice_id)->first();
        

        $return_amount = Invoice::where('id',$request->invoice_id)->update([

            'return_amount' => $request->total_return_paid,
            'total_paid' => 0,
            'total_due' => 0,
        ]);

        if($total_due->total_due == 0 ){
        // dd($request->all());
            $return = new ReturnTbl();
            $return->date = $request->date;
            $return->invoice_id = $request->invoice_id;
            $return->customer_id = $request->customer_id;

            $return->estimated_amount = $request->estimated_amount;
            $return->discount = $request->discount_amount;
            $return->discount_amount = $request->discount;
            $return->total_return = $request->total_return_paid;

            $return->created_by = auth()->user()->id;

            DB::transaction(function () use ($request, $return) {

                $total_paid = Invoice::where('id',$request->invoice_id)->first();
                
                if ($return->save()) {
                    // dd(count($request->invoiceItem_id));
                    //save product_id and category_id in purchase_items table where $request->product_id is array of product_id
                    for ($i = 0; $i < count($request->item_id); $i++) {
                        $returnItem = new ReturnItem();
                        $returnItem->return_id = $return->id;
                        $returnItem->product_id = $request->product_id[$i];
                        $returnItem->rate = $request->new_rate[$i];
                        $returnItem->main_qty = $request->main_qty[$i];
                        $returnItem->sub_qty = $request->sub_qty[$i];
                        $returnItem->subtotal = $request->total_return_paid[$i];
                        $returnItem->created_at = $request->date;
                        $returnItem->save();
                    }
                    //create purchase log call createPurchaseLog function
                    $id = $return->id;
                    $type = 'Sale Return';
                    // dd($id);

                    // Transaction
                    $transaction = new Transaction();
                    $transaction->transaction_type = $type;
                    $transaction->date = date('Y-m-d');
                    $transaction->return_id = $id;
                    $transaction->customer_id = $request->customer_id;
                    $transaction->debit = NULL;
                    $transaction->credit = $request->total_return_paid;
                    $transaction->created_by = auth()->user()->id;
                    $transaction->save();
                    $this->createReturnLog($request, $id, $type);
                }
            });

        }else{

            $total_paid = Invoice::where('id',$request->invoice_id)->first();

            $return = new ReturnTbl();
            $return->date = $request->date;
            $return->invoice_id = $request->invoice_id;
            $return->customer_id = $request->customer_id;

            $return->estimated_amount = $request->estimated_amount;
            $return->discount = $request->discount_amount;
            $return->discount_amount = $request->discount;
            $return->total_return = $request->total_return_paid;

            $return->created_by = auth()->user()->id;

            DB::transaction(function () use ($request, $return) {
                
                $total_paid = Invoice::where('id',$request->invoice_id)->first();
                // dd($request->total_return_paid);
                if ($return->save()) {
                    // dd(count($request->invoiceItem_id));
                    //save product_id and category_id in purchase_items table where $request->product_id is array of product_id
                    for ($i = 0; $i < count($request->item_id); $i++) {
                        $returnItem = new ReturnItem();
                        $returnItem->return_id = $return->id;
                        $returnItem->product_id = $request->product_id[$i];
                        $returnItem->rate = $request->new_rate[$i];
                        $returnItem->main_qty = $request->main_qty[$i];
                        $returnItem->sub_qty = $request->sub_qty[$i];
                        $returnItem->subtotal = $request->total_return_paid[$i];
                        $returnItem->created_at = $request->date;
                        $returnItem->save();
                    }
                    //create purchase log call createPurchaseLog function
                    $id = $return->id;
                    $type = 'Sale Return';
                    // dd($id);
                    // Transaction
                    $transaction = new Transaction();
                    $transaction->transaction_type = $type;
                    $transaction->date = date('Y-m-d');
                    $transaction->return_id = $id;
                    $transaction->customer_id = $request->customer_id;
                    $transaction->debit = NULL;
                    $transaction->credit = $request->total_return_paid;
                    $transaction->created_by = auth()->user()->id;
                    $transaction->save();
                    $this->createReturnLog($request, $id, $type);
                }
            });

        }
            notify()->success('Return Created Successfully');
            return redirect()->route('return.sale');
                        
    
    }

    public function delete($id)
    {
        $return = ReturnTbl::find($id);
        $transactions = Transaction::where('return_id', $return->id)->get();
        $bank_transaction = BankTransaction::where('return_id', $return->id)->get();
        foreach ($transactions as $transaction) {
            if ($transaction->actual_pay_id != NULL) {
                $actualpay = ActualPayment::where('id', $transaction->actual_pay_id)->first();
                $actualpay->amount -= $transaction->debit;
                if ($actualpay->amount <= 0) {
                    $actualpay->delete();
                } else {
                    $actualpay->save();
                }
            }
            $transaction->delete();
        }
        foreach ($bank_transaction as $bank) {
            $bank->delete();
        }
        $return->delete();
        notify()->success('Return deleted successfully');
        return back();
    }

    function createReturnLog(Request $request, $id, $type)
    {
        // if ($request->main_qty[$i] == $request->new_main_qty[$i]) {

            // dd('return qty equal');
            Invoice::where('id', $request->invoice_id)->update([
                'status' => 2,
            ]);

            // if ($request->payable_amount > 0) {

                $total_paid = Invoice::where('id',$request->invoice_id)->first();
                //create bank transaction
                $bank_transaction = new BankTransaction();
                $bank_transaction->trans_type = 'withdraw';
                $bank_transaction->date = date('Y-m-d');
                $bank_transaction->bank_id = $request->bank_id;
                $bank_transaction->return_id = $id;
                $bank_transaction->amount = $request->return_cus_amount;
                $bank_transaction->created_by = auth()->user()->id;
                $bank_transaction->save();

                // Transaction
                $transaction = new Transaction();
                $transaction->transaction_type = 'Return Money to customer';
                $transaction->date = date('Y-m-d');
                $transaction->bank_id = $request->bank_id;
                $transaction->return_id = $id;
                $transaction->customer_id = $request->customer_id;
                $transaction->debit = $request->return_cus_amount;
                $transaction->credit = NULL;
                $transaction->created_by = auth()->user()->id;
                $transaction->save();
            // }
        
    }
}
