<?php

namespace App\Http\Controllers\Bill;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Http\Requests\Bill\BillRequest;
use App\Bill\Bill_category;
use App\Bill\Bill_subcategory;
use App\Bill\Bill_payable;
use App\Bill\Bill_installment;
use App\Head;
use EF;
use Session;
use App\Account;
use Illuminate\Contracts\Encryption\DecryptException;
use Crypt;

class BillController extends Controller
{

    public function billandpayments(Request $request)
    {
      try{
        $this->monthlyPayableCreate();
      $type = "";
      $billexpensetypes = EF::getBillExpenseType();
      if ($request->expense_type)
      {
        $type = $request->expense_type;
        if($type == "Administrative" || $type == "Cost of Sales")
        {
          $type = $request->expense_type;
        }
        else {
          parent::errorMessage('Something Went Wrong.');
          return redirect()->back();
        }
      }
      else{
        $type = "Cost of Sales";
      }
        $bill_category = new Bill_category;
        $categories = $bill_category->getCategoryList($type);

        return view('bills.billandpayments',
        	[
            'billexpensetypes' => $billexpensetypes,
            'categories' =>$categories,
            'selected' =>$type
        	]
    );
  }

  catch (DecryptException $e)
  {
      //
  }

    }

    public function commit_category(BillRequest $request)
    {
      try{

        $form_collect = $request->input();
        $bill_category = new Bill_category;

        $check_category = $bill_category->checkCategory($form_collect['name'], $form_collect['expense_type']);
        if($check_category == 1)
        {
          parent::errorMessage('Name Already Exists.');
          return redirect()->back();
        }
        $head          = new Head;
        $curr_bill = $bill_category->createCategory($form_collect);

        if(isset($curr_bill->id))
        {

          $head_data['bill_category_id'] = $curr_bill->id;

          $head_data['branch'] = 1;
          $head_data['code']   = '556';
          $head_data['name']   = $curr_bill->name;
          $head_data['flag']   = 1;

          if($curr_bill->expense_type == 'Cost of Sales')
          {

             $head_data['nature']   = 'Expense - Cost of Sales';

          }
          elseif($curr_bill->expense_type == 'Administrative')
          {
             $head_data['nature']   = 'Expense';

          }

          $curr_head = $head->storeHead($head_data);

          if(isset($curr_head->id))
          {


          parent::setLogMessage($curr_bill->name.' Category has been saved.');
          parent::successMessage('Category has been saved.',parent::getLogMessage());


          }

        }

        else
        {
          parent::errorMessage('Something Went Wrong.');

        }
    }


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

}

public function bill_category(Request $request)
{

  try{
    $id = decrypt($request->id);
    $bill_category = new Bill_category;
    $curr_category = $bill_category->getCategoryByID($id);
    if(isset($curr_category->id))
    {
      $Bill_payable = new Bill_payable;
      $curr_payable = $Bill_payable->getPayableList($curr_category->id);
      $bill_subategory = new Bill_subcategory;
      $curr_subategory = $bill_subategory->getSubCategoryList($curr_category->id);
      $laibilitytype = EF::getBillLaibilityType();
      $payabletype = EF::getBilPayableType();
      return view('bills.category_bills' , ['curr_subategory'=>$curr_subategory,'curr_payable'=>$curr_payable,'category_id'=>$id, 'laibilitytype'=>$laibilitytype,'payabletype'=>$payabletype]);
    }

    else{
      parent::errorMessage('Something Went Wrong.');
      return redirect()->back();
    }
}


catch (DecryptException $e)
{

}

}



public function commitSubcategory(BillRequest $request)
        {

          try{
            
            $id = decrypt($request->category_id);
            $bill_category = new Bill_category;
            $curr_category = $bill_category->getCategoryByID($id);


            if(isset($curr_category->id))
            {
              $form_collect = $request->input();
              $form_collect['bill_category_id'] = $id;
              $bill_subategory = new Bill_subcategory;
              $check_subcategory = $bill_subategory->checkCategory($form_collect['name'], $form_collect['bill_category_id']);

              if($check_subcategory == 1)
              {
                parent::errorMessage('Name Already Exists.');

                if($request->ajax())
                {
                   return ['success' => false];
                }
                else
                {
                  return redirect()->back();
                }
                
              }
              $curr_subcategory = $bill_subategory->createSubCategory($form_collect);
              if(isset($curr_subcategory->id))
              {

                $head = new Head;

                $category_head = $head->getHeadByBillCategoryId($curr_category->id);
             

                if(isset($category_head->id))
                {
                  $subhead = new Account;

                  $subhead_data['head_id']             = $category_head->id;
                  $subhead_data['bill_subcategory_id'] = $curr_subcategory->id;
                  $subhead_data['name']                = $curr_subcategory->name;
                  $subhead_data['flag']                = 1;
                  $subhead_data['scale_id']            = 0;
                  $subhead_data['designation_id']      = 0;
                  $subhead_data['user_id']             = 0;
                  $subhead_data['type']                = 'General';

                  $curr_subhead = $subhead->storeSubHead($subhead_data);


                  if(isset($curr_subhead->id))
                  {

              parent::setLogMessage('New sub category "'.$curr_subcategory->name.'" has been added.');

              parent::successMessage('New Sub category has been added.',parent::getLogMessage());
               if($request->ajax())
              {

                 $data['id']   = Crypt::encrypt($curr_subcategory->id);
                 $data['name'] = $curr_subcategory->name;
                 parent::clearMessageLog(1);
                 
                 return $data;
              }
                  }


                }

              }
            }
        }


        catch (DecryptException $e)
        {

        }
            

        return redirect()->back();

        }


  public function commit_bill(BillRequest $request)
                {

                  try{
                    $form_collect = $request->input();

                    $payabletype = $form_collect['payable_type'];
                    $laibilitytype = $form_collect['laibility_type'];
                    $amount = $form_collect['total'];
                    $description = $form_collect['description'];
                    $category_id = decrypt($form_collect['category_id']);
                    $subcategory_id = decrypt($form_collect['subcategory']);
                    $form_payable = [];
                    $form_installment = [];
                    $form_payable['bill_category_id'] = $category_id;
                    $form_payable['bill_subcategory_id'] = $subcategory_id;
                    $form_payable['laibility_type'] = $laibilitytype;
                    $form_payable['payable_type'] = $payabletype;
                    $form_payable['amount'] = $amount;
                    $form_payable['description'] = $description;
                    $form_payable['paid'] = "0";
                    $form_payable['no_of_month'] = 0;
                    $payable = new Bill_payable;
                    $installment = new Bill_installment;

                    if($payabletype == "One Time")
                    {
                      $form_payable['month_amount'] = $amount;
                      $form_payable['lifetime'] = "0";
                      $curr_payable = $payable->createPayable($form_payable);
                      if($curr_payable->id)
                      {
                        $form_installment['amount'] = $amount;
                        $form_installment['bill_payable_id'] = $curr_payable->id;
                        $form_installment['paid_amount'] = "0";
                        $form_installment['to_pay'] = $amount;
                        $form_installment['installment_no'] = "1";
                        $curr_installment = $installment->createInstallment($form_installment);
                        if($curr_installment->id)
                        {
                        parent::setLogMessage(' Payable has been saved.');
                        parent::successMessage('Payable has been saved');
                        return redirect()->back();
                      }
                      }
                    }


                    if($payabletype == "Reoccuring")
                    {

                      if(array_key_exists("life",$form_collect))
                      {
                        $form_payable['month_amount'] = $amount;
                        $form_payable['lifetime'] = "1";
                        $curr_payable = $payable->createPayable($form_payable);
                        if($curr_payable->id)
                        {
                          $form_installment['amount'] = $amount;
                          $form_installment['bill_payable_id'] = $curr_payable->id;
                          $form_installment['paid_amount'] = "0";
                          $form_installment['to_pay'] = $amount;
                          $form_installment['installment_no'] = "1";
                          $curr_installment = $installment->createInstallment($form_installment);
                          if($curr_installment->id)
                          {
                          parent::setLogMessage(' Payable has been saved.');
                          parent::successMessage('Payable has been saved');
                          return redirect()->back();
                        }
                        }
                      }
                      else
                      {
                      
                        $form_payable['no_of_month'] = $form_collect['noofmonth'];
                          $form_payable['month_amount'] = $amount / $form_payable['no_of_month'];
                        $form_payable['lifetime'] = "0";
                        $curr_payable = $payable->createPayable($form_payable);
                        if($curr_payable->id)
                        {
                          $ins_amount = $amount/$form_collect['noofmonth'];
                          for($i=0 ;$i<$form_collect['noofmonth'];$i++)
                          {
                          $form_installment['amount'] = $ins_amount;
                          $form_installment['bill_payable_id'] = $curr_payable->id;
                          $form_installment['paid_amount'] = "0";
                          $form_installment['to_pay'] = $amount;
                          $form_installment['installment_no'] = $i+1;
                          $curr_installment = $installment->createInstallment($form_installment);
                          }

                          parent::setLogMessage(' Payable has been saved.');
                          parent::successMessage('Payable has been saved');
                          return redirect()->back();
                      }


                    }

                }

              }
                catch (DecryptException $e)
                {

                }

                return redirect()->back();

                }


      public function show_bill_installments(Request $request)
      {

        try{
          $id = decrypt($request->id);
          $Bill_payable = new Bill_payable;
          $curr_payable = $Bill_payable->getPayableByID($id);
          if(isset($curr_payable->id))
          {
            $bill_installment = new Bill_installment;
            $curr_installments = $bill_installment->getInstallmentList($curr_payable->id);
            return view('bills.billInstallment' , ['curr_installments'=>$curr_installments,'curr_payable'=>$curr_payable]);
          }

          else{
            parent::errorMessage('Something Went Wrong.');
            return redirect()->back();
          }
      }


      catch (DecryptException $e)
      {

      }

      }

      public function monthlyPayableCreate()
      {

        try{
          $form_installment = [];
          $installment = new Bill_installment;
          $Bill_payable = new Bill_payable;
          $curr_payable = $Bill_payable->getPayableMonthly();

          foreach($curr_payable as $pay)
          {

            $form_installment['amount'] = $pay->amount;
            $form_installment['bill_payable_id'] = $pay->id;
            $form_installment['paid_amount'] = "0";
            $form_installment['to_pay'] = $pay->amount;
            $lastest = $installment->getInstallmentLast($pay->id);
            $latest_no = (int)$lastest->installment_no;
            $form_installment['installment_no'] = $latest_no+1;
            if(strtotime($lastest->created_at) < strtotime('-30 days')) {
            $curr_installment = $installment->createInstallment($form_installment);
          }
          }

          return;
      }


      catch (DecryptException $e)
      {

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


}
