<?php

namespace App\Http\Controllers\Accounts\Incomes;

use App\Traits\Uploads;
use Illuminate\Support\Str;
use App\Classes\DepositType;
use Illuminate\Http\Request;
use App\Models\Accounts\Item\Item;
use App\Http\Controllers\Controller;
use App\Models\Accounts\Charthistory;
use App\Models\Accounts\Income\Invoice;
use Illuminate\Support\Facades\Session;
use App\Models\Accounts\Income\Customer;
use App\Http\Requests\Income\CreditRequest;
use App\Models\Accounts\CharthistoryParent;
use App\Models\Accounts\Income\CreditMemoItem;
use App\Models\Accounts\Income\InvoiceHistory;
use App\Models\Accounts\Income\InvoicePayment;
use App\Models\Accounts\Income\CreditMemoModel;
use App\Models\Accounts\Income\InvoiceCustomers;
use App\Models\Accounts\Income\CreditMemoInvoices;
use App\Models\Accounts\Accounting\Chartofaccounts;
use App\Models\Accounts\Income\CreditMemoCustomers;

class CreditMemos extends Controller
{
    use Uploads;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $creditmemo = CreditMemoModel::all();

        return view('accounts.incomes.creditmemo.index',compact('creditmemo'));    
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $elements = Customer::whereEnabled(1)->select('name', 'id','parent_id')->get()->toArray();

        $customers = app('App\Http\Controllers\Accounts\Incomes\Customers')->bulidCustomer($elements);

        $customer_id = isset($id)?$id:0;

        $item_elements = Item::whereEnabled(1)->select('id','name','subitem')->get()->toArray();

        $items  = $this->bulidItems($item_elements);


        return view('accounts.incomes.creditmemo.create',compact('customers','customer_id','items'));
    }

    function bulidItems(array $elements, $parentId = NULL) {
            $child = array();
        
            foreach ($elements as $element) {
                if ($element['subitem'] == $parentId) {

                    $children = $this->bulidItems($elements, $element['id']);

                        if (!empty($children) > 0 ) {
                            $element['children'] = $children;
                        }

                    $child[] = $element;
                }
            }
        return $child;
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreditRequest $creditrequest)
    {       
        $creditrequest['customer_address'] = $creditrequest->address;
        $date = $this->date_format_change_unique($creditrequest->creditmemo_at);
        $creditrequest['company_id']      = session('company_id');
        $creditrequest['creditmemo_at'] = date("Y-m-d", strtotime($date[0]));
        $paid_at  = date("Y-m-d", strtotime($date[0]));
        $customer = Customer::find($creditrequest->customer_id);
        $creditrequest['customer_name']  = $customer->name;
        $credit_memo = CreditMemoModel::create($creditrequest->all());

        // Upload attachment
        if ($creditrequest->file('attachment')) {
            $media = $this->getMedia($creditrequest->file('attachment'), 'creditmemo');
            $credit_memo->attachMedia($media, 'attachment');
        }

        $sub_total = 0;

        $chart_history = [];
        $chart_history['company_id'] = session('company_id');
        $chart_history['transaction_id'] = $credit_memo->id;
        $chart_history['transaction_type'] = 'Credit Memo';
        $chart_history['currency_code'] = 'USD';
        
        $chart_history['name'] = $customer->name;
        $chart_history['transaction_date'] = date("Y-m-d", strtotime($date[0]));

        if ($creditrequest['item']) {
            foreach ($creditrequest['item'] as $item) {
                $item_sku = '';
                if (!empty($item['item_id'])) {
                    $item_object = Item::find($item['item_id']);
                    $chart_object = Chartofaccounts::find($item['chartid']);
                }

                $credit_memo_item['item_id'] = $item['item_id'];
                $credit_memo_item['company_id'] = session('company_id');
                $credit_memo_item['company_id'] = session('company_id');
                $credit_memo_item['name'] = Str::limit($item['name'], 180, '');
                $credit_memo_item['quantity'] = $item['quantity'];
                $credit_memo_item['price'] = $item['price'];
                $credit_memo_item['chartid'] = $item['chartid'];
                $credit_memo_item['total'] = $item['price'] * $item['quantity'];
                $credit_memo_item['credit_memo_id'] = $credit_memo->id;

                CreditMemoItem::create($credit_memo_item);

                // Set Chart History.
                
                $chart_history['amount_type'] = DepositType::find($item['chartid'],'debit');
                $chart_history['chartofaccount_id'] = $item['chartid'];
                $chart_history['account_type_id'] = $chart_object['account_type_id'];
                $chart_history['detail_type'] = $chart_object['detail_type'];
                $chart_history['amount'] = $item['price'] * $item['quantity'];
                $chart_history['description'] = $creditrequest->notes;

                $chart_history_id = Charthistory::create($chart_history);

                $chartparents = app('App\Http\Controllers\Accounts\Accounting\Accounting')->parent_chartaccount_id($item['chartid']);

                CharthistoryParent::charthistoryparentsave($chart_history_id->id,$chartparents->original['parent_id_string'],$item['chartid']); 

                $sub_total += $credit_memo_item['total'];
            }
        }
        

        $customer_parent = app('App\Http\Controllers\Accounts\Incomes\Customers')->parent_customer_id($customer->id);

        $customer_parent_list = explode(',',$customer_parent->original['parent_id_string']); 
        $customer_parent = array_push($customer_parent_list, $customer->id);

        foreach ($customer_parent_list as $key => $parent_list) {
            if($parent_list){
                $creditmemo_customer['company_id'] = session('company_id');
                $creditmemo_customer['creditmemo_id'] = $credit_memo->id;
                $creditmemo_customer['customer_id'] = $parent_list;
                $creditmemo_customer['total_amount'] = $sub_total;
                CreditMemoCustomers::create($creditmemo_customer);
            }
        }        

        $amount = $sub_total;
       
        if($creditrequest['invoice']){
            foreach($creditrequest['invoice']  as $invoices_request){
                $invoice = Invoice::with('status','payments_total','payments','histories')->where('id',$invoices_request['invoice_id'])->first();
                if($invoice && $invoices_request['invoice_amount']){
                    $total_amount = $invoice->amount;
                    $invoice_paid_amount = $invoices_request['invoice_amount'];
                    if ($invoice->payments()->count()) {
                        $total_amount -= $invoice->payments()->paid();
                    }
                    if ($invoice_paid_amount == $total_amount) {
                        $invoice->invoice_status_code = 'paid';
                    } else if($invoice_paid_amount <= $total_amount){
                        $invoice->invoice_status_code = 'partial';
                    }else {
                        $invoice->invoice_status_code = 'partial';
                    }
                    $invoice->save();

                    $invoice_payment = new InvoicePayment;
                    $invoice_payment->paid_at = $paid_at;
                    $invoice_payment->customer_id = $creditrequest->customer_id;
                    $invoice_payment->company_id = $invoice->company_id;
                    $invoice_payment->currency_code = 'USD';
                    $invoice_payment->amount = $invoices_request['invoice_amount'];
                    $invoice_payment->invoice_id = $invoice->id;
                    $invoice_payment->save();

                    $invoice_history = new InvoiceHistory;
                    $invoice_history->company_id = session('company_id');
                    $invoice_history->invoice_id = $invoice->id;
                    $invoice_history->status_code = $invoice->invoice_status_code;
                    $invoice_history->notify = '0';
                    $invoice_history->description = '$' .$sub_total .' Credit Memo';
                    $invoice_history->save();

                    $creditmemoinvoice = new CreditMemoInvoices; 
                    $creditmemoinvoice->company_id = session('company_id');
                    $creditmemoinvoice->invoice_id = $invoice->id;
                    $creditmemoinvoice->credit_memo_id = $credit_memo->id;
                    $creditmemoinvoice->amount       = $invoices_request['invoice_amount'];
                    $creditmemoinvoice->invoice_num  = $invoice->invoice_number;
                    $creditmemoinvoice->save();
                }
            }     
        }

        if($amount!= '0'){
            $credit_memo->status = 'closed';
            $credit_memo->remaining_balance = $amount;
        }else{
            $credit_memo->status = 'closed';
            $credit_memo->remaining_balance = '0';
        }
        $credit_memo->total = $sub_total;
        $credit_memo->update();


        //History For Account Receiveble
        $chart =  Chartofaccounts::where('name','=','Accounts Receivable')->first();
        $chart_history = [];
        $chart_history['company_id'] = session('company_id');
        $chart_history['transaction_id'] = $credit_memo->id;
        $chart_history['transaction_type'] = 'Credit Memo';
        $chart_history['currency_code'] = 'USD';
        $chart_history['amount_type'] = DepositType::find($chart->id,'credit');
        $chart_history['name'] = $customer->name;
        $chart_history['chartofaccount_id'] = $chart->id;
        $chart_history['account_type_id'] = $chart->account_type_id;
        $chart_history['detail_type'] = $chart->detail_type;
        $chart_history['amount'] = $sub_total;
        $chart_history['description'] = 'Credit Memo';
        $chart_history['transaction_date'] = date("Y-m-d", strtotime($date[0]));
        $chart_history_id = Charthistory::create($chart_history);

        $chartparents = app('App\Http\Controllers\Accounts\Accounting\Accounting')->parent_chartaccount_id($chart->id);

        CharthistoryParent::charthistoryparentsave($chart_history_id->id,$chartparents->original['parent_id_string'],$chart->id); 

         $message = trans('messages.success.added', ['type' => trans_choice('general.creditmemo', 1)]);

        Session::flash('success', $message);

        return redirect('incomes/creditmemo/'.$credit_memo->id);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(CreditMemoModel $creditmemo)
    {


        return view('accounts.incomes.creditmemo.show',compact('creditmemo'));
    }


    public function getinvoices($customer_id)
    {
           $invoices = [];
           $invoicelist =  InvoiceCustomers::with(['invoice' => function($query){
                $query->where('invoices.invoice_status_code', '!=', 'paid');
           }])->where('customer_id',$customer_id)->get();
           foreach ($invoicelist as $key => $item) {
              if($item->invoice){
               array_push($invoices,$item->invoice);
              }
           }
    
            $invoices = collect($invoices);
        return view('accounts.incomes.creditmemo.getinvoices',compact('invoices'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('accounts.incomes.creditmemo.edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        return view('accounts.incomes.creditmemo.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return view('accounts.incomes.creditmemo.index');
    }
}
