<?php

namespace App\Http\Controllers\Accounts\Banking;

use App\Traits\Uploads;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Accounts\Charthistory;
use App\Models\Accounts\Expense\Vendor;
use Illuminate\Support\Facades\Session;
use App\Models\Accounts\Banking\Journal;
use App\Models\Accounts\Income\Customer;
use App\Models\Accounts\CharthistoryParent;
use App\Models\Accounts\Banking\JournalItem;
use App\Models\Accounts\Accounting\Chartofaccounts;

class JournalController extends Controller
{
    use Uploads;

    public $personname = [];
    
    public function index()
    {
        $journals = Journal::latest()->get()->collect();

        return view('accounts.banking.journal.index',compact('journals'));        
    }

    public function create()
    {
        $this->addJournals(Customer::select(DB::raw('CONCAT(id,"-",1) as idconcate'),'name')->get(), 'Customer');
        $this->addJournals(Vendor::select(DB::raw('CONCAT(id,"-",2) as idconcate'),'name')->get(), 'Vendor');

        $personname = $this->getPersonname();

        return view('accounts.banking.journal.create',compact('personname'));
    }

    protected function getPersonname()
    {       
        $personname = collect($this->personname);
       
        return $personname;
    }

    protected function addJournals($items,$type)
    {
        foreach ($items as $item) {
           $data = [ 
            'id' => $item->idconcate,
            'name' => $item->name,
            'type' => $type
           ];
        $this->personname[] = (object) $data;
        }
    }

    public function store(Request $request)
    {
        $date = $this->date_format_change_unique($request->journal_date);
        $request['journal_date'] = date('Y-m-d', strtotime($date[0]));
        $request['journal_number'] = $request->journal_number;
        $request['company_id'] = session('company_id');
        $request['amount'] = $request->amount;
        $request['description'] = $request->description;
        
        $journal = Journal::create($request->all());

        // Upload attachment
        if ($request->file('attachment')) {
            $media = $this->getMedia($request->file('attachment'), 'journal');

            $journal->attachMedia($media, 'attachment');
        }

        $chart_history = [];
        $chart_history['company_id'] = session('company_id');
        $chart_history['transaction_id'] = $journal->id;
        $chart_history['transaction_type'] = 'Journal';
        $chart_history['number'] = $journal->journal_number;
        $chart_history['currency_code'] = 'USD';

        if ($request['journal']) {
            foreach ($request['journal'] as $item) {
                if($item['chart_id']){
                    $chart_object = Chartofaccounts::find($item['chart_id']);

                    $journal_item['chart_id'] = $item['chart_id'];
                    $journal_item['company_id'] =  session('company_id');
                    $journal_item['debit'] = $item['debits'];
                    $journal_item['credit'] = $item['credits'];
                    $journal_item['description'] = $item['descriptions'];
                    $journal_item['person_id'] = $item['person_id'];
                    $journal_item['journal_id'] = $journal->id;
                    
                    JournalItem::create($journal_item);

                    // Set Chart History.
                    $chart_history['chartofaccount_id'] = $item['chart_id'];
                    $chart_history['account_type_id'] = $chart_object['account_type_id'];
                    $chart_history['detail_type'] = $chart_object['detail_type'];
                    $chart_history['amount'] = isset($item['debits'])?$item['debits']:$item['credits'];
                    $chart_history['description'] = $item['descriptions'];
                    $chart_history['amount_type'] = isset($item['debits'])?'add':'sub';
                    $chart_history['transaction_id'] = $journal->id;

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


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

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

                }
            }
        }
        
        $message = trans('messages.success.added', ['type' => trans_choice('general.journal', 2)]);

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

        return redirect('banking/journal');        
    }

    public function edit($id)
    {
        $journal = Journal::with(['items'])->whereId($id)->first();
        
        $this->addJournals(Customer::select(\DB::raw('CONCAT(id,"-",1) as idconcate'),'name')->get(),trans_choice('general.customers', 1));
        $this->addJournals(Vendor::select(\DB::raw('CONCAT(id,"-",2) as idconcate'),'name')->get(),trans_choice('general.vendors', 1));

        $personname = $this->getPersonname();
        
        return view('accounts.banking.journal.edit',compact('personname', 'journal'));
    }

    public function update(Request $request, $id)
    {
        // dd($request->all());
        $journal = Journal::whereId($id)->first();
        $date = $this->date_format_change_unique($request->journal_date);
        $request['journal_date'] = date('Y-m-d', strtotime($date[0]));
        $request['journal_number'] = $request->journal_number;
        $request['company_id'] = session('company_id');
        $request['amount'] = $request->amount;
        $request['description'] = $request->description;

        $journal = Journal::find($id);
        $journal->fill($request->all())->save();

        // Upload attachment
        if ($request->file('attachment')) {
            $media = $this->getMedia($request->file('attachment'), 'journal');

            $journal->attachMedia($media, 'attachment');
        }

        // Delete All Items for Journal
        JournalItem::whereJournal_id($id)->delete();
        Charthistory::whereTransaction_type('Journal')->whereTransaction_id($id)->delete();

        $chart_history = [];
        $chart_history['company_id'] = session('company_id');
        $chart_history['transaction_id'] = $journal->id;
        $chart_history['transaction_type'] = 'Journal';
        $chart_history['number'] = $journal->journal_number;
        $chart_history['currency_code'] = 'USD';

        if ($request['journal']) {
            foreach ($request['journal'] as $item) {
                if($item['chart_id']){
                    $chart_object = Chartofaccounts::find($item['chart_id']);

                    $journal_item['chart_id'] = $item['chart_id'];
                    $journal_item['company_id'] =  session('company_id');
                    $journal_item['debit'] = $item['debits'];
                    $journal_item['credit'] = $item['credits'];
                    $journal_item['description'] = $item['descriptions'];
                    $journal_item['person_id'] = $item['person_id'];
                    $journal_item['journal_id'] = $journal->id;
                    
                    JournalItem::create($journal_item);

                    // Set Chart History.
                    $chart_history['chartofaccount_id'] = $item['chart_id'];
                    $chart_history['account_type_id'] = $chart_object['account_type_id'];
                    $chart_history['detail_type'] = $chart_object['detail_type'];
                    $chart_history['amount'] = isset($item['debits'])?$item['debits']:$item['credits'];
                    $chart_history['description'] = $item['descriptions'];
                    $chart_history['amount_type'] = isset($item['debits'])?'add':'sub';
                    $chart_history['transaction_id'] = $journal->id;
                    $chart_history['transaction_type'] = 'Journal';

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

                    $chartparents = app('App\Http\Controllers\Accounts\Accounting\Accounting')->parent_chartaccount_id($item['chart_id']);
 
                    CharthistoryParent::charthistoryparentsave($chart_history_id->id,$chartparents->original['parent_id_string'],$item['chart_id']);
                }
            }
        }

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

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

        return redirect('banking/journal/'.$id.'/edit');
    }
}
