<?php
namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

/**
 * Description of history
 *
 * @author Phattharaphon
 */
class History extends Authenticatable {
     use HasFactory, Notifiable;

    protected $table = 'history'; // Set custom table name
    protected $fillable = ['user_id']; // Add more fields if needed. $fillable, Laravel prevents saving data.
    protected $primaryKey = 'userId'; // Set primary key to user_id
    
    static public function getUserHistory($user_id)
    {
        try {
            $userHistoryObj = History::where('userId', $user_id)->get();
            $userHistory = NULL;
            foreach($userHistoryObj as $userHistoryKey => $userHistoryVal){
                $userHistory = $userHistoryVal;
            }
            //dd($userHistory);
            return  $userHistory;
        } catch (\Exception $e) {
            //logging $e
            echo "error = .$e->getMessage())";
            return false;
        }
    }    

    static public function getUserToolHistoryCount()
    {
        //waiting update
    }
    
    static public function getHistoryByToolId($accountCode, $toolId=0)
    {
        /// get Accounts by accountCode
        if($accountCode === ""){
            return NULL;
        }
        $accountInfo = DB::table('accounts')
                        ->select('*')
                        ->where('accounts.accountCode', $accountCode)
                        ->first();
        if($accountInfo){
            return false;
        }
                
        try {
            $userId = $accountInfo->userId;
            if($userId && $toolId){
                $userToolHistoryObj = History::where('userId', $userId)->where('toolId', $toolId)->get();
            }elseif($userId && !$toolId){
                $userToolHistoryObj = History::where('userId', $userId)->get();
            }

            $userToolHistory = NULL;
            foreach($userToolHistoryObj as $userHistoryKey => $userHistoryVal){
                $userToolHistory = $userHistoryVal;
            }
            dd($userToolHistory);
            return  $userToolHistory;
        } catch (\Exception $e) {
            //logging $e
            //echo "error = .$e->getMessage())";
            return false;
        }
    }

}//end class
