<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use EF;
use App\Account;
use App\Branch;
use App\Http\Requests\AccountRequest;
use Illuminate\Contracts\Encryption\DecryptException;
use Crypt;
use App\Journal;
use App\Transaction;
use App\Head;
use App\Bank;
use App\User;


class AccountController extends Controller
{
   
    
    public function index($id)
    {  

        try 
        {
            $id = decrypt($id);

            $head = new Head;

            $curr_head = $head->getHeadById($id);

            if(isset($curr_head->id))
            {
                $account = new Account();

                $bank = new Bank;

                $subhead=$account->getSubHeadByHead($id);

                $series = $account->generateSubheadCode($id);

                return view('accounts.manage_subhead',
                    [
                        'series'         =>  $series['code'],
                        'subhead'        =>  $subhead,
                        'head_id'        =>  $id, 
                        'head'           =>  $curr_head,
                        'bank_list'      =>  $bank->getAllBanks(),

                    ]);
            }



            

        } 
        catch (DecryptException $e) 
        {
            //
        }
        
        return redirect()->back();
        
    }

    public function storeSubHead(AccountRequest $request)
    {   
        $form_collect = $request->input();
        $id=$form_collect['head_id'];
        $form_collect['head_id'] = decrypt($form_collect['head_id']);
        $form_collect['bank']    = decrypt($form_collect['bank']);

         if(isset($form_collect['debit_account']))
        {
            $form_collect['debit_account'] = decrypt($form_collect['debit_account']);
        }
        else if(isset($form_collect['credit_account']))
        {
            $form_collect['credit_account'] = decrypt($form_collect['credit_account']);
        }


        $form_collect['user_id']        = null;
        $form_collect['scale_id']       = null;
        $form_collect['designation_id'] = null;


        

        $subhead = new Account;
        $journal = new Journal;


        $curr_subhead = $subhead->storeSubHead($form_collect);
        
        if(isset($curr_subhead->id))
        {
            
            parent::setLogMessage($curr_subhead->code.' subhead has been created.');

            parent::successMessage('Subhead has been created.',parent::getLogMessage());

            if($request->ajax())
            {
                $head = $curr_subhead->head;

                $data['head_tag'] = 'head_section_'.$head->code;
                
                $subhead['subhead'] = $subhead->getSubHeadByHead($head->id);

                $subhead['head']    = $head;

                $subhead['journal'] = $journal;

                $data['subhead_view'] = view('components.subhead.subhead_table',$subhead)->render();



                return $data;
            }
        }

        return redirect('subhead/'.$id);
    }

    public function updateSubHead(AccountRequest $request)
    {   

        
        try 
        {
            $form_collect = $request->input();
            
            $form_collect['subhead_id'] = decrypt($form_collect['subhead_id']);

            $form_collect['bank'] = decrypt($form_collect['bank']);

            
            if(isset($form_collect['debit_account']))
            {
                $form_collect['debit_account'] = decrypt($form_collect['debit_account']);
            }
            else if(isset($form_collect['credit_account']))
            {
                $form_collect['credit_account'] = decrypt($form_collect['credit_account']);
            }

           
            $subhead = new Account;

            $journal = new Journal;

            $curr_subhead = $subhead->updateSubHead($form_collect);

            if(isset($curr_subhead->id))
            {
                parent::setLogMessage($curr_subhead->code.' subhead has been updated.');

                parent::successMessage('Subhead has been updated.',parent::getLogMessage());

                if($request->ajax())
                {
                    $head = $curr_subhead->head;

                    $data['head_tag'] = 'head_section_'.$head->code;
                    
                    $subhead['subhead'] = $subhead->getSubHeadByHead($head->id);

                    $subhead['head']    = $head;

                    $subhead['journal']    = $journal;



                    $data['subhead_view'] = view('components.subhead.subhead_table',$subhead)->render();



                    return $data;
                }
            }
        } 
        catch (DecryptException $e) 
        {
            
        }

        return redirect()->back();
    }

    public function removeSubHead($id)
    {   

        parent::errorMessage('Subhead not found.');

        try 
        {
            $id = decrypt($id);
            $subhead = new Account;

            $curr_subhead = $subhead->removeSubHead($id);
            
            if(isset($curr_subhead->id))
            {
                parent::setLogMessage($curr_subhead->code.' subhead has been deleted.');

                parent::successMessage('Subhead has been deleted.',parent::getLogMessage());

                if(\Request::ajax())
                {
                    $head = $curr_subhead->head;

                    $data['head_tag'] = 'head_section_'.$head->code;
                    
                    $subhead['subhead'] = $subhead->getSubHeadByHead($head->id);

                    $subhead['head']    = $head;

                    $data['subhead_view'] = view('components.subhead.subhead_table',$subhead)->render();



                    return $data;
                }
            } 
        } 
        catch (DecryptException $e) 
        {
            
        }

        return redirect()->back();
    }


    public function getSubHeadDropdown($id)
    {  

            $id = decrypt($id);
         
            $account = new Account();
            $subhead = $account->getSubHeadByHead($id);
            $view = '<option value="'.Crypt::encrypt(0).'">Select Sub Head</option>';

            foreach($subhead as $rows)
        {
          $view .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->name.'</option>';
        }

        return $view;
     
        
    }

    public function getSubheadTypeDropDown($voucher_type)
    {

        $data = array(

            'filter_subhead_list' => '<option value="'.Crypt::encrypt(0).'">Select SubHead</option>',
            'subhead_list'        => '<option value="'.Crypt::encrypt(0).'">Select SubHead</option>',
            'voucher_type'        =>  $voucher_type,

        );


        try
        {
            $account = new Account;


            $filter_subhead_list = $account->getAllSubheadByType($voucher_type);

            $subhead_list        = $account->getAllSubhead();


            foreach($filter_subhead_list as $rows)
            {
              $data['filter_subhead_list'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->head->code.' '.$rows->head->name.' | '.$rows->code.' '.$rows->name.'</option>';
            }

            foreach($subhead_list as $rows)
            {
              $data['subhead_list'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->head->code.' '.$rows->head->name.' | '.$rows->code.' '.$rows->name.'</option>';
            }
        }
        catch (DecryptException $e) 
        {
                               
        }

        return $data;
    }

    public function viewLedger($id)
    {
        $id = Crypt::decrypt($id);

        $subhead = new Account;
        $branch = new Branch;

        $journal = new Journal;

        $journal_list=$journal->getJournalByAccountId($id,[EF::getFirstBranch()]);

        // dd($journal_list);
        $data = [

            'journal_list' => $this->filterAccounts($journal_list)

        ];
    
        return view('accounts.view_ledger',
            [ 
                'view_ledger' =>   view('components.subhead.table_subhead_ledger',$data),
                'account_id'   =>   $id,
                'subhead'      =>   $subhead->getSubHeadById($id),
                'branch'       =>   $branch->getBranchList(),
                'voucher_id'   =>   uniqid(),

            ]);
    }

    public function viewUserLedger($id)
    {
        $id = Crypt::decrypt($id);

        $subhead = new Account;
        $branch = new Branch;
        $user = new User;

        $journal = new Journal;

        $journal_list=$journal->getJournalByUserId($id,[EF::getFirstBranch()]);

        $curr_user = $user->getUserById($id);

        $data = [

            'journal_list' => $this->filterAccounts($journal_list)

        ];
    
        return view('accounts.view_user_ledger',
            [ 
                'view_ledger'  =>   view('components.subhead.table_user_subhead_ledger',$data),
                'user_id'      =>   $id,
                'curr_user'    =>   $curr_user,
                'branch'       =>   $branch->getBranchList(),
                'voucher_id'   =>   uniqid(),

            ]);
    }

    function filterAccounts($journal_list)
    {   
        $flag = "";

        $ledger_data = array();
        $count = 0;

        foreach ($journal_list as $rows) 
        {
            $voucher_number = $rows->transaction->voucher_type.'-'.$rows->transaction->voucher_number;

            
            if($rows->transaction->compound_type === EF::getVoucherType()['2'] && $rows->debit > 0)
            {

                if($voucher_number != $flag)
                {
                    $rows->debit = $rows->transaction->total_amount;
                    $ledger_data[$count] = $rows;
                    $count++;

                }
                else
                {
                    unset($rows);
                }
            }
            else if($rows->transaction->compound_type === EF::getVoucherType()['1'] && $rows->credit > 0)
            {

                if($voucher_number != $flag)
                {
                    $rows->credit = $rows->transaction->total_amount;
                    $ledger_data[$count] = $rows;
                    $count++;
                }
                else
                {

                    unset($rows);
                }
            }
            else
            {
                $ledger_data[$count] = $rows;
                $count++;
            }

            $flag = $voucher_number;
        }

        return $ledger_data;
    }

    public function showBookingLedger($booking_id)
    {
        if(\Request::ajax())
        {
            try
            {
                $view = '';

                $booking_id = decrypt($booking_id);



                $journal = new Journal;

                $account_condition = ['booking_id' => $booking_id];

                $transaction_condition = [];

                $journal_list = $journal->accountWiseReport('1970-01-01','2099-01-01',$account_condition,$transaction_condition);


                $key = 0;
                $count = 0;

                foreach ($journal_list as $rows) 
                {

                    if($rows->transaction->status == "Approve" || $rows->transaction->status == "Reversal")
                    {
                        if($key != $rows->transaction_id)
                        {
                             $view.='<tr>
                                <td>'.++$count.'</td>
                                
                                <td>'.$rows->transaction->voucher_type.'-'.$rows->transaction->voucher_number.'</td>

                                <td>'.wordwrap($rows->narration,40,'<br>').'</td>


                                <td>'.EF::numberFormat($rows->transaction->total_amount).'</td>
                                <td>'.EF::dateFormat($rows->transaction->created_at).'</td><td>';

                                if($rows->transaction->status == "Approve")
                                {
                                    $view.='<span class="badge badge-success">'.EF::getstatus($rows->transaction->status).'</span>';
                                } 
                                    
                                else if($rows->transaction->status == "Reversal")
                                {
                                    $view.='<span class="badge badge-primary">'.EF::getstatus($rows->transaction->status).'</span>';
                                } 
                                    
                                else
                                {
                                    $view.='<span class="badge badge-warning"> '.$rows->transaction->status.'</span>';
                                }
                               
                                

                                $view.='</td><td> <a target="_blank" href="voucherpreview/'.Crypt::encrypt($rows->transaction_id).'"><i class="fa fa-print"></i> Print</a></td>

                                </tr>';
                        }
                        
                      

                        $key = $rows->transaction_id; 
                    }
                    

                    
                }


                echo $view;
            }
            catch (DecryptException $e) 
            {
               

                return redirect('home')->back(); 
                        
            }
            


        }
        else
        {
            return redirect('home');
        }
    }

    public function showCancelBookingLedger($booking_id)
    {
        if(\Request::ajax())
        {
            try
            {
                $view = '';

                $booking_id = decrypt($booking_id);



                $journal = new Journal;

                $account_condition = ['booking_id' => $booking_id];

                $transaction_condition = [];

                $journal_list = $journal->accountWiseReport('1970-01-01','2099-01-01',$account_condition,$transaction_condition);

                $key = 0;
                $count = 0;

                foreach ($journal_list as $rows) 
                {

                    if($rows->transaction->status == "Approve" || $rows->transaction->status == "Reversal")
                    {
                        if($key != $rows->transaction_id)
                        {
                             $view.='<tr>
                            
                                <td>'.++$count.'</td>
                                
                                <td>'.$rows->transaction->voucher_type.'-'.$rows->transaction->voucher_number.'</td>

                                <td>'.wordwrap($rows->narration,40,'<br>').'</td>


                                <td>'.EF::numberFormat($rows->transaction->total_amount).'</td>
                                <td>'.EF::dateFormat($rows->transaction->created_at).'</td><td>';

                                if($rows->transaction->status == "Approve")
                                {
                                    $view.='<span class="badge badge-success">'.EF::getstatus($rows->transaction->status).'</span>';
                                } 
                                    
                                else if($rows->transaction->status == "Reversal")
                                {
                                    $view.='<span class="badge badge-primary">'.EF::getstatus($rows->transaction->status).'</span>';
                                } 
                                    
                                else
                                {
                                    $view.='<span class="badge badge-warning"> '.$rows->transaction->status.'</span>';
                                }
                               
                                

                                $view.='</td><td> <a target="_blank" href="voucherpreview/'.Crypt::encrypt($rows->transaction_id).'"><i class="fa fa-print"></i> Print</a></td>

                                </tr>';
                        }
                        
                      

                        $key = $rows->transaction_id; 
                    }
                    

                    
                }


                echo $view;
            }
            catch (DecryptException $e) 
            {
               

                return redirect('home')->back(); 
                        
            }
            


        }
        else
        {
            return redirect('home');
        }
    }

    public function getRetainEarning($profit_loss = [])
    {
         $total_income = 0;
         $total_cost_sale = 0;
         $total_expense = 0;
         $expense = '';
         $revenue = '';
         $cost_of_sale = '';

        /*
           :::::::::: PROFIT RULE LIST ::::::::::: 
           DEBIT  - CREDIT USE ASSET & EXPENSE CASE  
           CREDIT - DEBIT  USE INCOME LIABILTY & CAPITAL CASE
           CREDIT - DEBIT RESULT ALWAYS POSITVE USING PHP abs(result)
        */
        
        // GET NATURE LIST
        $nature_list = EF::getNatureList();

        foreach($profit_loss as $rows)
        {
            // NATURE[5] == REVENUE  
            if($rows->nature == $nature_list['5'])
            {
               $revenue .= '<tr>
                    <td>'.$rows->name.'</td>
                    <td>'.EF::numberFormat(($rows->credit - $rows->debit)).'</td>
                    <td></td>
                </tr>';
              
              $total_income += ($rows->credit - $rows->debit);
            }
            elseif($rows->nature == $nature_list['6']) //  NATURE[4] == EXPENSE-COST OF SALE
            {
                $cost_of_sale .= '<tr>
                    <td>'.$rows->name.'</td>
                    <td>'.EF::numberFormat(($rows->debit - $rows->credit)).'</td>
                    <td></td>
                </tr>';
              
                $total_cost_sale += ($rows->debit - $rows->credit);
            }
              
        }

        foreach($profit_loss as $rows)
        {
            //  EXPENSE
            if($rows->nature == $nature_list['7'])
            {
                $expense .= '<tr>
                        <td>'.$rows->name.'</td>
                        <td>'.EF::numberFormat(($rows->debit - $rows->credit)).'</td>
                        <td></td>
                      </tr>';

                $total_expense += ($rows->debit - $rows->credit);
            }
        }

                    
        return [

            'total_income'      => $total_income,
            'total_cost_sale'   => $total_cost_sale,
            'total_expense'     => $total_expense,
            'expense'           => $expense,
            'revenue'           => $revenue,
            'cost_of_sale'      => $cost_of_sale,
            'gross_profit'      => ($total_income - $total_cost_sale),
            'net_profit'        => (($total_income - $total_cost_sale) - $total_expense),
        ];
    }

    function showSubheadModal($id)
    {
        if(\Request::ajax())
        {
            try 
        {
            $id = decrypt($id);

            $head = new Head;

            $curr_head = $head->getHeadById($id);

            if(isset($curr_head->id))
            {
                $account = new Account();

                $bank = new Bank;

                $subhead=$account->getSubHeadByHead($id);

                $series = $account->generateSubheadCode($id);

                return view('components.subhead.modals.add_subhead',
                    [
                        'series'         =>  $series['code'],
                        'subhead'        =>  $subhead,
                        'head_id'        =>  $id, 
                        'head'           =>  $curr_head,
                        'bank_list'      =>  $bank->getAllBanks(),
                        'subhead_list'   =>  $account->getAllSubheadByNature($curr_head->nature),


                    ]);
            }



            

        } 
        catch (DecryptException $e) 
        {
            //
        }

           
        }

        return redirect('home');
    }

    function showUpdateSubheadModal($id)
    {
        if(\Request::ajax())
        {
            try 
            {
                $id = decrypt($id);

                $account = new Account();

                $curr_subhead = $account->getSubheadById($id);

            

                if(isset($curr_subhead->id))
                {
                    $head = new Head;

                    $account = new Account;

                    $journal = new Journal;

                    $bank = new Bank;

                    $curr_head = $head->getHeadById($curr_subhead->head_id);

                    return view('components.subhead.modals.update_subhead',
                        [
                      
                            'subhead'        =>  $curr_subhead,
                            'head_id'        =>  $id, 
                            'head'           =>  $curr_head,
                            'bank_list'      =>  $bank->getAllBanks(),
                            'journal'        =>  $journal,
                            'subhead_list'   =>  $account->getAllSubheadByNature($curr_head->nature),


                        ]);
                }



            

        } 
        catch (DecryptException $e) 
        {
            //
        }

           
        }

        return redirect('home');
    }

    
    public function getPaymentOptionDropDown(Request $request)
    {   
        $data = [
                    'debit_list' => '<option value="'.Crypt::encrypt(0).'">Select Debit Account</option>', 

                    'credit_list' => '<option value="'.Crypt::encrypt(0).'">Select Credit Account</option>',
                ];

        $debit_list  = [];
        $credit_list = [];

        if(\Request::ajax())
        {
            $account = new  Account;

            if(isset($request->payment_option) && $request->payment_option  === "Pay Now")
            {

                $debit_list   = $account->getAccountListByNature(['Short-term Liability','Expense','Cost of Sales']);
                 

                 $credit_list  = $account->getAccountListByType(['Cash','Bank']);

            }
            else if(isset($request->payment_option) && $request->payment_option  === "Pay Later")
            {
                $debit_list   = $account->getAccountListByNature(['Expense','Cost of Sales']);
                

                $credit_list  = $account->getAccountListByType(['General']);
            }

                foreach($debit_list as $rows)
                {
                  $data['debit_list'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->head->code.' '.$rows->head->name.' | '.$rows->code.' '.$rows->name.'</option>';
                }

                foreach($credit_list as $rows)
                {
                  $data['credit_list'] .= '<option value="'.Crypt::encrypt($rows->id).'">'.$rows->head->code.' '.$rows->head->name.' | '.$rows->code.' '.$rows->name.'</option>';
                }

        }

        return $data;
    }



}
