<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;
use Schema;

class ImportDataModel extends Model
{
    public function joinBaceSingleColumnUpdate($data)
    {
    	// THIS FUNCTION REQUIREMENT PARAMETTER
    	// 1. PARENT TABLE NAME
    	// 2. CHILD  TABLE NAME
    	// 3. PARENT COLUMN NAME
    	// 4. CHILD  COLUMN NAME
    	// 5. SET COLUMN NAME (COLUMN SETTER)
        // 6. FETCH COLUMN NAME (COLUMN GETTER)


        return  DB::transaction(function () use ($data)  {

            // CHECK TABLE NAMES
            if(Schema::hasTable($data['parent_table'],$data['child_table']))
            {
                // CHECK PARENT AND CHILD TABLE COLUMNS
                if(Schema::hasColumn($data['parent_table'],$data['column_setter'],$data['parent_column']) && Schema::hasColumn($data['child_table'],$data['child_column'],$data['column_getter']))
                {

                    $custom_query = "UPDATE ".$data['parent_table']." SET ".$data['column_setter']." = (SELECT ".$data['child_table'].".".$data['column_getter']." FROM ".$data['child_table']." WHERE (".$data['parent_table'].".".$data['parent_column']." = ".$data['child_table'].".".$data['child_column']." ) )";


                    DB::statement($custom_query);
                }
                
                 echo ucwords($data['parent_table']).' => <= '.$data['child_table'].' succssfully replace. <br>';
                
                return true;
            }
            else
            {
                echo ucwords($data['parent_table']).' => <= '.$data['child_table'].' failed. <br>';
                return false;
            }

        });

    	
    	
    }


    public function storeTableData($table,$data_list)
    {
    	if(Schema::hasTable($table))
    	{

    		return  DB::transaction(function () use ($table,$data_list)  {

    			
    			 DB::table($table)->insert($data_list);

                 echo ucwords($table).' succssfully insert. <br>';
			});
    	}

        echo ucwords($table).' failed. <br>';
    	
    }

    public function updateTableData($table,$key_column,$list = [],$update_column = [])
    {
        if(Schema::hasTable($table) && Schema::hasColumn($table,$key_column))
        {
            return  DB::transaction(function () use ($table,$key_column,$list,$update_column)  {
                
                 DB::table($table)->whereIn($key_column,$list)->update($update_column);

                 echo ucwords($table).' succssfully updated. <br>';
            });
        }

        echo ucwords($table).' failed. <br>';
        
    }




    public function exportTableData($table)
    {
    	if(Schema::hasTable($table))
    	{
    		return DB::table($table)->get();
		}

		return false;
    }

    public function countDataBySpecficTable($table,$key_column,$value_column)
    {
        if(Schema::hasTable($table) && Schema::hasColumn($table,$key_column))
        {
            return DB::table($table)->where($key_column,$value_column)->count();
        }

        return false;
    }

    public function getMaxByTable($table,$key_column,$matching_column = 0,$value_column = 0)
    {
        if(Schema::hasTable($table) && Schema::hasColumn($table,$key_column))
        {
            if($value_column === 0 && $matching_column === 0)
            {
                return DB::table($table)->max($key_column);
            }
            else
            {
                return DB::table($table)->where($key_column,$value_column)->max($key_column);
            }
        }

        return false;
    }

    public function getMixByTable($table,$key_column,$matching_column = 0,$value_column = 0)
    {
        if(Schema::hasTable($table) && Schema::hasColumn($table,$key_column))
        {
            if($value_column === 0 && $matching_column === 0)
            {
                return DB::table($table)->min($key_column);
            }
            else
            {
                return DB::table($table)->where($matching_column,$value_column)->min($key_column);
            }
        }

        return false;
    }

    public function getTableDataByColumn($table,$key_column,$value_column,$order)
    {
        if(Schema::hasTable($table) && Schema::hasColumn($table,$key_column,$order))
        {
            return DB::table($table)->where($key_column,$value_column)->orderBy($order,'asc')->get();   
        }

        return false;
    }

    public function storeTransaction($object)
    {

        return \DB::transaction(function () use ($object)  {
       
            
            $type = explode('/',$object->voucher_no);

            if(isset($type[0]))
            {
                $type = strtoupper($type[0]);

                if($type != "JV")
                {
                    $type = $type.'V';
                }
            }

            $transaction                    =  new Transaction;

            $transaction->status            = 'Approve';

            $transaction->voucher_type      =  $type;

            $transaction->voucher_number    =  $this->generateVoucherSerialNumber($type);

            $transaction->old_voucher       =  $object->voucher_no;

            $transaction->compound_type     =  'General';

            $transaction->total_amount      =  $object->amount;

            $transaction->created_at        =  date('Y-m-d',strtotime($object->created_at));

            $transaction->save();

            $this->storeJournal($object,$transaction->id,$type);
          
            return with($transaction);

        });
    }

    public function storeJournal($object,$transaction_id,$type)
    {
        // ACCOUNT ID => 1 MEAN ADVANCE FROM CUSTOMERS
        // ACCOUNT ID => 2 MEAN ADVANCE FROM OLD DATA JV ACCOUNTS
        // ACCOUNT ID => 3 MEAN CASH IN HAND
        // ACCOUNT ID => 4 MEAN BANK IN HAND

         return \DB::transaction(function () use ($object,$transaction_id,$type)  {

            $debit  = 0;
            $credit = 0;

            if(strtoupper($type) === "JV")
            {
                $debit  = 2;
                $credit = 1;
            }
            else
            {
                if(strtoupper($object->mode) === "CASH")
                {

                    $debit  = 3;
                    $credit = 1;
                }
                else
                {

                    $debit  = 4;
                    $credit = 1;
                }
            }

            $data = array( 

              'booking_id'      => $object->booking_id,
              'account_id'      => $debit,
              'payment_id'      => $object->id,
              'branch_id'       => $object->branch_id,
              'user_id'         => $object->user_id,
              'transaction_id'  => $transaction_id,
              'debit'           => $object->amount,
              'credit'          => 0,
              'narration'       => $object->narration,
              'mode'            => $object->mode,
              'drawn_on'        => $object->drawn_on,
              'instrument'      => $object->instrument,
              'instrument_date' => $object->instrument_date,
              'created_at'      => $object->created_at,

            );

            Journal::insert($data);

            $data['debit']      = 0;

            $data['credit']     = $object->amount;

            $data['account_id'] = $credit;

            Journal::insert($data);

            return with(true);
       



        });
     }

     public function generateVoucherSerialNumber($type)
     {
      
        $formattedNumber = null;

        $transaction = Transaction::where('voucher_type','=',$type)->max('voucher_number');

        if(isset($transaction))
        {     
            $formattedNumber = sprintf('%04d', ++$transaction);
        }
        else
        {
            $transaction = 1;
            $formattedNumber = sprintf('%04d', $transaction);
        }

        return $formattedNumber;
    } 

}
