<?php namespace App\Models;

use CodeIgniter\Model;
use App\Models\Mbookingdetails;
use App\Models\Mcategories;

class mBills extends Model {
    protected $table = 'budget_bills';

    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;

    protected $returnType = 'object';

    protected $useSoftDeletes = false;
    //TODO timestamps aktivieren
    // protected $createdField  = 'created_at';
    // protected $updatedField  = 'updated_at';
    // protected $deletedField  = 'deleted_at';

    protected $allowedFields = ['renummer','datum','receiver','source_id','amount','type','comment','validate','lkz','rechnung'];

    protected $useTimestamps = false;


    /**
	 * liefert Buchungen für Aktivitätenliste
	 * @return mixed  Datensätze für Tabelle
	 */
    public function getEntriesDet($start, $ende, $source){
        $details = model('App\Models\mBillDetails');
        $quelle = model('App\Models\mAccounts');
        $this->where('datum >=',  date( 'Y-m-d', strtotime($start)));
        $this->where('datum <=',  date( 'Y-m-d', strtotime($ende)));
        // alle Detailsbuchungen wo account id übereinstimmt
        if ($source > 0) {
            $subs = $details->select('bill_id')->where('account_id',$source)->findAll();
//            log_message('error', 'Get Entries Det {msg}', ['msg'=>(string)$this->db->getLastQuery()]);
            if (0 < sizeof($subs)){
                $keys=array();
                foreach ($subs as $value) {
                    $keys[] = intval($value->bill_id);
                }
                $this->groupStart();
                $this->where('source_id',  $source );
                $this->orWhereIn('id',  $keys );
                $this->groupEnd();
    
            } else {
                $this->where('source_id',  $source );
            }
        }

        $result = $this->orderBy('datum','desc')->where('lkz',null)->findAll();
        if (0 == sizeof($result)){
            return $result;
        }

        $keys=array();
        foreach ($result as $value) {
            $keys[] = intval($value->id);
        }
        $ergebnis = $details->getDetails($keys);
        
        foreach ($result as $value) {
            $value->details = $ergebnis[$value->id]??null;
            $value->datum =  date( "d.m.Y", strtotime( $value->datum ));
            $value->source = $quelle->getDropDownEntry($value->source_id);
//            $value->amount = number_format( $value->amount , 2, ',', '.' );
        }
        return $result;
     }

    /**
	 * liefert Buchungen für Übersichtstabelle
	 * @return mixed  Datensätze für Tabelle
	 */
    function getEntries(){
        $details = model('App\Models\mBillDetails');
        $quelle = model('App\Models\mAccounts');
        $result = $this->orderBy('datum','desc')->where('validate',false)->where('lkz',null)->findAll(10);
        $keys=array();
        foreach ($result as $value) {
            $keys[] = intval($value->id);
        }
        //$ergebnis = $details->whereIn('bill_id', $keys)->asArray()->findAll();
        $ergebnis = $details->getDetails($keys);
       // print_r($ergebnis);
        
        foreach ($result as $value) {
            $value->details = $ergebnis[$value->id]??null;//$details->getEntries($value->id);
            $value->datum =  date( "d.m.Y", strtotime( $value->datum ));
            $value->quelle = $quelle->getDropDownEntry($value->source_id);
//            $value->amount = number_format( $value->amount , 2, ',', '.' );
        }
        return $result;
     }

    /**
	 * liefert gegebene Buchung inkl. Details im Formularformat
     * @param int id der Buchung
	 * @return mixed  Datenstruktur für Formular
	 */
     function getEntry($id, &$result, $accounts){
        $details = model('App\Models\mBillDetails');
        $quelle = model('App\Models\mAccounts');
        $data = $this->orderBy('datum','desc')->find($id);
        $result['datum'] = $data->datum;//date( "d.m.Y", strtotime($data->datum));
        $result['receiver'] = $data->receiver;
        $result['billfile'] = $data->rechnung;
        $result['source'] = $data->source_id;
        $result['validate'] = $data->validate;
        $result['id'] = $id;
        $result = array_merge($result, $details->getEntriesForForm($id, $result, $accounts));
        $result['transfer'] = $result['transfer'] || ($data->type == 'transfer');
        return $result;
     }

     function getToDos(){
        $details = model('App\Models\mBillDetails');
        $quelle = model('App\Models\mAccounts');
        $result = $this->orderBy('datum','desc')->where('validate',true)->where('lkz',null)->findAll();
        $keys=array();
        foreach ($result as $value) {
            $keys[] = intval($value->id);
        }
        $ergebnis = $details->getDetails($keys);

        foreach ($result as $value) {
            $value->details = $ergebnis[$value->id]??null;
            //$value->details = $details->getEntries($value->id);
            $value->datum =  date( "d.m.Y", strtotime( $value->datum ));
            $value->quelle = $quelle->getDropDownEntry($value->source_id);;
//            $value->amount = number_format( $value->amount , 2, ',', '.' );
        }
        return $result;
     }
     function getAccountsBalance(){
        $sums = $this->db->query("SELECT * FROM get_account_balance4()");
        return $sums->getResult();
     }

     public function storeBillFile(int $billId, string $filename){
        $this->update($billId, [ 'rechnung' => $filename ]);
     }
     public function deleteBillFile(int $billId){
        $this->set('rechnung', 'NULL',false);
        $this->update($billId);
     }

     public function saveBill($data) : int {
        $details = model('App\Models\mBillDetails');
        $accounts = model('App\Models\mAccounts');
        $this->set('datum',  date( "Y-m-d", strtotime($data['datum'] ) ));
        
        $this->set('source_id', $data['source']);
        $total = floatval($data['total_in'])-floatval($data['total_out']);
        if ( !isset($data['multi']) )
            $total = floatval($data['input'][0])-floatval($data['output'][0]); 
        if ( isset($data['rechnung']) )
            $this->set('rechnung', $data['rechnung']);
        $this->set('amount', $total);
        $this->set('validate', $data['validate']??false);
        if ($data['transfer']==1){
            $this->set('receiver', $accounts->getDropDownEntry($data['category'][0]));
            $this->set('type', 'transfer');    
        }
        else{
            $this->set('receiver', $data['receiver']);
            $this->set('type', 'multiple');    
        }
        //$tabdata['type']
        if ( 0 == $data['id'] ){
             $this->insert();
             $billId = $this->getInsertID();
            //insert
        }
        else{
            $billId = $data['id'];
            $this->update($data['id']);
       }
        $details->saveEntries($data, $billId);
        return $billId;
    }

    /**
	 * löscht gegebene Buchung inkl. Details
     * @param int id der Buchung
	 * @return mixed  Datenstruktur für Formular
	 */
    function deleteEntry($id){
        $details = model('App\Models\mBillDetails');
        if ($id > 0){
            $details->where('bill_id',$id)->delete();
            $this->delete($id);
        }
     }
};
?>