<?php

namespace App\Models;

use App\Utils\Constants;
use PDO;
use App\Utils\Model;
use DateTime;

/**
 * This model is used to manage the calendar.
 *
 * @version    7.0.0
 * @since      Class available since version
 */

class JobargModuleModel extends Model
{

    public function getJaRunJobnetSummary(int $registryNumber)
    {
        $query = "
            select run_type, status, job_status, scheduled_time, start_time, end_time, jobnet_id, jobnet_name from ja_2_run_jobnet_summary_table where inner_jobnet_id = :inner_jobnet_id
            UNION ALL
            select run_type, status, job_status, scheduled_time, start_time, end_time, jobnet_id, jobnet_name from ja_2_ran_jobnet_summary_table where inner_jobnet_id = :inner_jobnet_id
        ";

        $this->db->query($query);
        $this->db->bind(':inner_jobnet_id', $registryNumber);

        return $this->db->resultSet();
    }

    public function getJaRunJob(int $registryNumber)
    {
        // Prepare the query
        $query = "
            SELECT inner_job_id, end_time
            FROM ja_2_run_job_table
            WHERE status IN (:statusEnd, :statusEndErr, :statusRunErr)
            AND job_type != :jobType
            AND inner_jobnet_main_id = :registryNumber

            UNION ALL

            SELECT inner_job_id, end_time
            FROM ja_2_ran_job_table
            WHERE status IN (:statusEnd, :statusEndErr, :statusRunErr)
            AND job_type != :jobType
            AND inner_jobnet_main_id = :registryNumber

            ORDER BY end_time ASC
        ";

        $this->db->query($query);
        $this->db->bind(':statusEnd', Constants::JA_JOB_STATUS_END);
        $this->db->bind(':statusEndErr', Constants::JA_JOB_STATUS_ENDERR);
        $this->db->bind(':statusRunErr', Constants::JA_JOB_STATUS_RUNERR);
        $this->db->bind(':jobType', Constants::JA_JOB_TYPE_END);
        $this->db->bind(':registryNumber', $registryNumber);

        return $this->db->resultSet();
    }


    public function getAfterVariable(int $innerJobId)
    {
        $query = "
            SELECT after_variable from ja_2_run_job_variable_table where inner_job_id = :inner_job_id
            UNION ALL
            SELECT after_variable from ja_2_ran_job_variable_table where inner_job_id = :inner_job_id
        ";

        $this->db->query($query);
        $this->db->bind(':inner_job_id', $innerJobId);

        return $this->db->resultSet();
    }

    public function getJobnetControl(string $jobnetId)
    {
        $this->db->query("select update_date, public_flag, multiple_start_up, user_name, jobnet_name, memo, jobnet_id from ja_2_jobnet_control_table where jobnet_id = '$jobnetId' and valid_flag=1");

        return $this->db->resultSet();
    }

    public function getJobExecAuth(string $jobnetId)
    {
        $this->db->query("select user_name, public_flag from ja_2_jobnet_control_table where jobnet_id = '$jobnetId' and valid_flag = 1");
        return $this->db->resultSet();
    }

    public function insertIntoJaRunJobnetVariable(int $innerJobnetId, string $beforeVariable)
    {
        $this->db->query('INSERT INTO ja_2_run_jobnet_variable_table (inner_jobnet_id, before_variable, seq_no) VALUES (:inner_jobnet_id, :before_variable, :seq_no)');

        $this->db->bind(':inner_jobnet_id', $innerJobnetId);
        $this->db->bind(':before_variable', $beforeVariable);
        $this->db->bind(':seq_no', 1);

        return $this->db->execute();
    }

    public function getHost(string $host)
    {
        $this->zabbixdb->query("select i.hostid, i.useip, i.dns, i.ip, h.status, i.port from hosts h, interface i where h.hostid = i.hostid and i.main = 1 and i.type = 1 and h.host = '$host'");

        return $this->zabbixdb->resultSet();
    }

    public function getUserId(string $username)
    {
        $this->zabbixdb->query("select userid from users where username = :username");
        $this->zabbixdb->bind(':username', $username);
        return $this->zabbixdb->execute();
    }

    public function checkUserStatus(string $userId)
    {
        $this->zabbixdb->query("select g.users_status from users_groups ug, usrgrp g where ug.usrgrpid = g.usrgrpid and ug.userid = :userId");
        $this->zabbixdb->bind(':userId', $userId);
        $row = $this->zabbixdb->single();
        if ($row === null) {
            return -1;
        }
        return (int)$row->users_status;
    }

    public function getUserType(string $userId)
    {
        $this->zabbixdb->query("select type from role r, users u WHERE u.roleid = r.roleid AND  u.userid = :userId");
        $this->zabbixdb->bind('userId', $userId);

        $data = $this->zabbixdb->single();
        if ($data === null) {
            return -1;
        }
        return (int)$data->type;
    }

    public function getUserLang(string $userId)
    {
        $this->zabbixdb->query("SELECT lang FROM users WHERE userid = :userId");
        $this->zabbixdb->bind(':userId', $userId);

        $data = $this->zabbixdb->single();

        if ($data === null || empty($data->lang)) {
            $this->logger->warning("User $userId not found, setting default lang to en_us");
            return "en_us";
        }
        $lang = strtolower($data->lang);
        $supportedLangs = ["en_us", "en_gb", "ja_jp", "ko_kr"];

        if (!in_array($lang, $supportedLangs, true)) {
            $this->logger->warning("User $userId lang '$lang' not supported, fallback to en_us");
            $lang = "en_us";
        }
        $this->logger->debug("User $userId language set to $lang");

        return $lang;
    }

    // public function streamJobLogs($job, $userLang, $user_type, $userId, $zabbixResult)
    // {
    //     // --- Step 1: Set headers for NDJSON streaming ---
    //     header('Cache-Control: no-cache');
    //     set_time_limit(0);

    //     error_reporting(E_ERROR | E_PARSE); // hide warnings/notices, only show fatal errors
    //     ini_set('display_errors', '0');     // do not send errors to output

    //     // --- Step 2: Disable PHP output buffering ---
    //     while (ob_get_level() > 0) ob_end_flush();
    //     ob_implicit_flush(true);

    //     // --- Step 3: Prepare SQL ---
    //     if (!empty($job['registry_number'])) {
    //         $whereSql = "a.inner_jobnet_main_id = :registry_number";
    //     } else {
    //         $whereSql = "a.log_date >= :from_time_start AND a.log_date <= :to_time_end";
    //         if (strlen($job['from_time']) === 8 && strlen($job['to_time']) === 8) {
    //             $fromDate = DateTime::createFromFormat('Ymd H:i:s', $job['from_time'] . ' 00:00:00');
    //             $toDate   = DateTime::createFromFormat('Ymd H:i:s', $job['to_time'] . ' 23:59:59');
                
    //             if (!$fromDate || !$toDate) {
    //                 throw new \Exception("Invalid date format.");
    //             }

    //             $from_time_start = $fromDate->getTimestamp();
    //             $to_time_end     = $toDate->getTimestamp();
    //         } else {
    //             throw new \Exception("Invalid from_time or to_time format.");
    //         }
    //     }

    //     $sql = "SELECT a.log_date, a.inner_jobnet_id, a.inner_jobnet_main_id, a.inner_job_id, a.update_date, 
    //                a.run_type, a.public_flag, a.jobnet_id, a.jobnet_name, a.job_id, a.job_name, a.user_name, 
    //                a.return_code, a.message_id, b.message
    //         FROM ja_2_run_log_table a
    //         JOIN ja_2_define_run_log_message_table b ON a.message_id = b.message_id
    //         WHERE $whereSql
    //           AND LOWER(b.lang) = :user_lang
    //         ORDER BY a.inner_jobnet_main_id, a.log_date";

    //     $stmt = $this->db->getDbHandler()->prepare($sql);

    //     // --- Step 4: Bind parameters ---
    //     if (!empty($job['registry_number'])) {
    //         $stmt->bindValue(':registry_number', $job['registry_number']);
    //     } else {
    //         $stmt->bindValue(':from_time_start', $from_time_start);
    //         $stmt->bindValue(':to_time_end', $to_time_end);
    //     }
    //     $stmt->bindValue(':user_lang', strtolower($userLang));

    //     $stmt->execute();

    //     $userIdCache = [];

    //     // --- Step 5: Stream each row ---
    //     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

    //         $public_flag = (int)$row['public_flag'];
    //         $jobnet_id   = $row['jobnet_id'];
    //         $job_id      = $row['job_id'];
    //         $user_name   = $row['user_name'];

    //         if (!isset($userIdCache[$user_name])) {
    //             $userIdCache[$user_name] = $this->getUserId($user_name);
    //         }
    //         $userid2 = $userIdCache[$user_name];
    //         $user_cmp = $this->checkCountUserGroup($userId, $userid2) > 0 ? 1 : 0;

    //         if (!($user_type === 3 || $public_flag === 1 || $user_cmp === 1)) {
    //             continue;
    //         }

    //         $update_date = date('Y-m-d H:i:s', (int)$row['update_date']);

    //         $log = [
    //             'log_date'             => $row['log_date'],
    //             'inner_jobnet_main_id' => $row['inner_jobnet_main_id'],
    //             'jobnet_id'            => $jobnet_id,
    //             'run_type'             => $row['run_type'],
    //             'public_flag'          => $row['public_flag'],
    //             'job_id'               => $job_id,
    //             'message_id'           => $row['message_id'],
    //             'message'              => $row['message'],
    //             'jobnet_name'          => $row['jobnet_name'],
    //             'job_name'             => $row['job_name'],
    //             'user_name'            => $user_name,
    //             'update_date'          => $update_date,
    //             'exist_cd'             => $row['return_code'] ?? ''
    //         ];

    //         // --- Step 6: Send JSON line safely ---
    //         $meta = [
    //             'Zabbix' => [
    //                 'jsonrpc' => '2.0',
    //                 'result'  => $zabbixResult['sessionid'],
    //                 'id'      => $zabbixResult['userid']
    //             ],
    //             'JobArranger' => [
    //                 'result' => true,
    //                 'log'    => $log
    //             ]
    //         ];

    //         // Use error_log for debugging instead of echo
    //         error_log("Streaming log: " . json_encode($log));

    //         // Echo only the JSON line for Go
    //         echo json_encode($meta, JSON_UNESCAPED_UNICODE) . "\n";
    //         flush();
    //         if (ob_get_level() > 0) {
    //             ob_flush();
    //         }
    //     }
    // }


    public function streamJobLogs($job, $userLang, $user_type, $userId, $zabbixResult)
    {
        // Step 1: headers and buffering (same as before)
        header('Cache-Control: no-cache');
        set_time_limit(0);
        error_reporting(E_ERROR | E_PARSE);
        ini_set('display_errors', '0');
        while (ob_get_level() > 0) ob_end_flush();
        ob_implicit_flush(true);

        // Step 2: Determine time range or registry_number for filtering
        if (!empty($job['registry_number'])) {
            $whereSql = "a.inner_jobnet_main_id = :registry_number";

            // Step 3: New - check if username is set in $job and user permission

            $filterUsername = !empty($job['target_user']) ? $job['target_user'] : null;
            if ($filterUsername !== null) {
                // Get userId of that username
                $userid2 = $this->getUserId($filterUsername);
                $this->logger->info("User id 2". $userid2);
                // Check if current user has permission to see this user’s logs
                $user_cmp = $this->checkCountUserGroup($userId, $userid2) > 0 ? 1 : 0;

                if (!($user_type === 3 || $user_cmp === 1)) {
                    // No permission: maybe throw exception or return empty?
                    // I'll assume empty result:
                    return; // or you can echo empty NDJSON line and exit
                }

                // Add username filter to WHERE clause
                $whereSql .= " AND a.user_name = :user_name";
            }

            $filterJobnetId = !empty($job["jobnetId"]) ? $job["jobnetId"] : null;
            if($filterJobnetId !== null) {
                $whereSql .= " AND a.jobnet_id = :jobnet_id";
            }

            $filterJobId = !empty($job["jobid"]) ? $job["jobid"] : null;
            // $this->logger->info("Jon id type". gettype($filterJobId));
            if($filterJobId !== null){
                $whereSql .= " AND a.job_id = :job_id";
            } 

        } else {
            function getTimestampFromDate($dateStr, $format) {
                $date = DateTime::createFromFormat($format, $dateStr);
                if (!$date) {
                    throw new \Exception("Invalid date format: " . $dateStr);
                }
                return $date->getTimestamp();
            }

            // Ensure 'from_time' and 'to_time' are valid and formatted correctly
            $from_time = $job['from_time'];
            $to_time   = $job['to_time'];

            // Case 1: Both from_time and to_time are 8 characters (YYYYMMDD)
            if (strlen($from_time) === 8 && strlen($to_time) === 8) {
                // Start of day for from_time and end of day for to_time
                $from_time_start = getTimestampFromDate($from_time . ' 00:00:00', 'Ymd H:i:s');
                $to_time_end     = getTimestampFromDate($to_time . ' 23:59:59', 'Ymd H:i:s');
            }
            // Case 2: Both from_time and to_time are 12 characters (YYYYMMDDHHMM)
            elseif (strlen($from_time) === 12 && strlen($to_time) === 12) {
                // Full date and time for both
                $from_time_start = getTimestampFromDate($from_time, 'YmdHi');
                $to_time_end     = getTimestampFromDate($to_time, 'YmdHi');
            }
            // Case 3: from_time is 8 characters (YYYYMMDD) and to_time is 12 characters (YYYYMMDDHHMM)
            elseif (strlen($from_time) === 8 && strlen($to_time) === 12) {
                // Start of day for from_time and full date/time for to_time
                $from_time_start = getTimestampFromDate($from_time . ' 00:00:00', 'Ymd H:i:s');
                $to_time_end     = getTimestampFromDate($to_time, 'YmdHi');
            }
            // Case 4: from_time is 12 characters (YYYYMMDDHHMM) and to_time is 8 characters (YYYYMMDD)
            elseif (strlen($from_time) === 12 && strlen($to_time) === 8) {
                // Full date/time for from_time and end of day for to_time
                $from_time_start = getTimestampFromDate($from_time, 'YmdHi');
                $to_time_end     = getTimestampFromDate($to_time . ' 23:59:59', 'Ymd H:i:s');
            }
            // Case 5: Invalid format
            else {
                throw new \Exception("Invalid from_time or to_time format.");
            }
            $whereSql = "a.log_date >= :from_time_start AND a.log_date <= :to_time_end";

            $filterUsername = !empty($job['target_user']) ? $job['target_user'] : null;
            if ($filterUsername !== null) {
                // Get userId of that username
                $userid2 = $this->getUserId($filterUsername);
                $this->logger->info("User id 2". $userid2);
                // Check if current user has permission to see this user’s logs
                $user_cmp = $this->checkCountUserGroup($userId, $userid2) > 0 ? 1 : 0;

                if (!($user_type === 3 || $user_cmp === 1)) {
                    // No permission: maybe throw exception or return empty?
                    // I'll assume empty result:
                    return; // or you can echo empty NDJSON line and exit
                }

                // Add username filter to WHERE clause
                $whereSql .= " AND a.user_name = :user_name";
            }

            $filterJobnetId = !empty($job["jobnetId"]) ? $job["jobnetId"] : null;
            if($filterJobnetId !== null) {
                $whereSql .= " AND a.jobnet_id = :jobnet_id";
            }

            $filterJobId = !empty($job["jobid"]) ? $job["jobid"] : null;
            $this->logger->info("Jon id type". gettype($filterJobId));
            if($filterJobId !== null){
                $whereSql .= " AND a.job_id = :job_id";
            }   

        }

        $whereSql1 = $whereSql;
        $whereSql2 = $whereSql;

        // Replace parameter names in $whereSql for second table to be unique (e.g., :user_name -> :user_name2)
        $whereSql2 = str_replace(
            ['a.', ':registry_number', ':user_name', ':jobnet_id', ':job_id', ':from_time_start', ':to_time_end'],
            ['b.', ':registry_number2', ':user_name2', ':jobnet_id2', ':job_id2', ':from_time_start2', ':to_time_end2'],
            $whereSql2
        );

        $sql = "
            SELECT
                a.log_date, a.inner_jobnet_id, a.inner_jobnet_main_id, a.inner_job_id, a.update_date,
                a.run_type, a.public_flag, a.jobnet_id, a.jobnet_name, a.job_id, a.job_name, a.user_name,
                a.return_code, a.message_id, c.message,
                'ja_2_run_log_table' AS source
            FROM ja_2_run_log_table a
            JOIN ja_2_define_run_log_message_table c 
            ON a.message_id = c.message_id AND LOWER(c.lang) = :user_lang1
            WHERE $whereSql1

            UNION ALL

            SELECT
                b.log_date, b.inner_jobnet_id, b.inner_jobnet_main_id, b.inner_job_id, b.update_date,
                b.run_type, b.public_flag, b.jobnet_id, b.jobnet_name, b.job_id, b.job_name, b.user_name,
                b.return_code, b.message_id, c.message,
                'ja_2_ran_log_table' AS source
            FROM ja_2_ran_log_table b
            JOIN ja_2_define_run_log_message_table c 
            ON b.message_id = c.message_id AND LOWER(c.lang) = :user_lang2
            WHERE $whereSql2

            ORDER BY inner_jobnet_main_id, log_date;
        ";

        // $this->logger->info("Sql query . ". $sql);
        $this->logger->debug('Params: ' . json_encode([
            ':registry_number'  => $job['registry_number'] ?? null,
            ':registry_number2' => $job['registry_number'] ?? null,
            ':user_lang1'       => strtolower($userLang),
            ':user_lang2'       => strtolower($userLang),
            // add other bound parameters here
        ]));
        $stmt = $this->db->getDbHandler()->prepare($sql);

        if (!empty($job['registry_number'])) {
            $stmt->bindValue(':registry_number', $job['registry_number']);
            $stmt->bindValue(':registry_number2', $job['registry_number']);
        } else {
            $stmt->bindValue(':from_time_start', $from_time_start);
            $stmt->bindValue(':to_time_end', $to_time_end);
            $stmt->bindValue(':from_time_start2', $from_time_start);
            $stmt->bindValue(':to_time_end2', $to_time_end);
        }

        if ($filterUsername !== null) {
            $stmt->bindValue(':user_name', $filterUsername);
            $stmt->bindValue(':user_name2', $filterUsername);
        }

        if ($filterJobnetId !== null) {
            $stmt->bindValue(':jobnet_id', $filterJobnetId);
            $stmt->bindValue(':jobnet_id2', $filterJobnetId);
        }

        if ($filterJobId !== null) {
            $stmt->bindValue(':job_id', $filterJobId);
            $stmt->bindValue(':job_id2', $filterJobId);
        }

        $stmt->bindValue(':user_lang1', strtolower($userLang));
        $stmt->bindValue(':user_lang2', strtolower($userLang));

        $stmt->execute();
        $error = $stmt->errorInfo();
        if ($error[0] != '00000') {
            $this->logger->error("SQL error: " . json_encode($error));
        }

        // Step 6: Now just stream all rows, no permission filter per row needed because pre-filtered by SQL and user permission
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // Check if public_flag or user_type === 3 or public_flag=1 etc is still needed?
            // If yes, keep the check here, otherwise remove.

            $public_flag = (int)$row['public_flag'];

            // Since you already checked permission based on username, you can skip some checks here,
            // or keep if needed to filter by public_flag or user_type
            $this->logger->debug("User Type". $user_type);
            $this->logger->debug('Public flag'.$public_flag);

            if (!($user_type === 3 || $public_flag === 1)) {
                continue;
            }

            if($row['update_date'] !== 0 && !empty($row['update_date']) && $row['update_date'] !== null){
                $update_date = date('Y-m-d H:i:s', (int)$row['update_date']);
            }
            if($row['log_date'] !== 0 && !empty($row['log_date']) && $row['log_date'] !== null){
                $log_date = date('Y-m-d H:i:s', (int)$row['log_date']);
            }

            $this->logger->debug("Result row". json_encode($row));

            $log = [
                'log_date'             => $log_date,
                'inner_jobnet_main_id' => $row['inner_jobnet_main_id'],
                'inner_jobnet_id'      => $row['inner_jobnet_id'],
                'run_type'             => $row['run_type'],
                'public_flag'          => $row['public_flag'],
                'jobnet_id'            => $row['jobnet_id'],
                'job_id'               => $row['job_id'],
                'message_id'           => $row['message_id'],
                'message'              => $row['message'],
                'jobnet_name'          => $row['jobnet_name'],
                'job_name'             => $row['job_name'],
                'user_name'            => $row['user_name'],
                'update_date'          => $update_date,
                'exist_cd'             => $row['return_code'] ?? ''
            ];

            $meta = [
                'Zabbix' => [
                    'jsonrpc' => '2.0',
                    'result'  => $zabbixResult['sessionid'],
                    'id'      => $zabbixResult['userid']
                ],
                'JobArranger' => [
                    'result' => true,
                    'log'    => $log
                ]
            ];

            error_log("Streaming log: " . json_encode($log));
            echo json_encode($meta, JSON_UNESCAPED_UNICODE) . "\n";
            flush();
            if (ob_get_level() > 0) ob_flush();
        }
    }



    public function checkCountUserGroup(string $userId1, string $userId2)
    {
        $this->zabbixdb->query("select count(*) as cnt from users_groups g1, users_groups g2 where g1.usrgrpid = g2.usrgrpid and g1.userid =:userId1 and g2.userid=:userId2");
        $this->zabbixdb->bind(':userId1', $userId1);
        $this->zabbixdb->bind(':userId2', $userId2);
        $rows = $this->zabbixdb->resultSet();
        return (int) ($rows[0]->cnt ?? 0);
    }

    public function getCountJaRunJobnetTable(string $startTime, string $jobnetId)
    {   
        $this->db->query("SELECT count(*) AS cnt from ja_2_run_jobnet_table where scheduled_time = :start_time and jobnet_id = :jobnet_id and run_type = :run_type");
        $this->db->bind(':start_time', $startTime);
        $this->db->bind(':jobnet_id', $jobnetId);
        $this->db->bind(':run_type', Constants::JA_JOBNET_RUN_TYPE_SCHEDULED);
        $rows = $this->db->resultSet();
        return (int) ($rows[0]->cnt ?? 0); 
    }

    public function getUsernameAndPublicFlag(string $innerJobnetId)
    {
        $this->db->query("select user_name, public_flag from ja_2_run_jobnet_table where inner_jobnet_id = :inner_jobnet_id");
        $this->db->bind(':inner_jobnet_id', $innerJobnetId);
        $result = $this->db->resultset();
        return $result;
    }

    public function checkUserGroup(string $userId, string $userId1)
    {
        $this->db->query("select count(*) from users_groups g1, users_groups g2 where g1.usrgrpid = g2.usrgrpid and g1.userid = :user and g2.userid = :user1");
        $this->db->bind(':user', $userId);
        $this->db->bind(':user1', $userId);
        $result = $this->db->resultset();
        return $result;
    }

        public function getJobnetGetJobId(string $innerJobnetId, string $jobnetId, string $jobid)
    {
        $this->logger->debug(">> getJobnetGetJobId called with jobid=$jobid, jobnetid=$jobnetId, inner_jobnet_id=$innerJobnetId");

        if (empty($innerJobnetId) || empty($jobid)) {
            $this->logger->error("Missing jobid or inner_jobnet_id");
            return 0;
        }

        $innerJobId = 0;
        $linkInnerJobnetId = $innerJobnetId;

        // Only if innerJobId > 0, check linked jobnet (currently will not run)
        if ($innerJobId > 0) {
            $this->db->query("SELECT link_inner_jobnet_id FROM ja_2_run_icon_jobnet_table WHERE inner_job_id = :inner_job_id");
            $this->db->bind('inner_job_id', $innerJobId);
            $linkedRows = $this->db->resultSet();

            return $linkedRows;
        }

        // Fetch from ja_2_run_job_table
        $this->db->query("SELECT inner_job_id, status, job_type FROM ja_2_run_job_table WHERE inner_jobnet_id = :inner_jobnet_id AND job_id = :job_id");
        $this->db->bind('inner_jobnet_id', $linkInnerJobnetId);
        $this->db->bind('job_id', $jobid);
        $rows = $this->db->resultSet();

        return $rows;
    }

    public function jobReleaseJobIdUpdate(string $innerJobId, int $actionFlag)
    {
        $this->db->query("UPDATE ja_2_run_job_table set method_flag = :method_flag where inner_job_id = :inner_job_id");
        $this->db->bind(':inner_job_id', $innerJobId);
        $this->db->bind(':method_flag', 0);
        $result = $this->db->execute();
        return $result;
    }

    public function jobReleaseJobIdInsert(string $innerJobId, string $innerJobnetId, int $actionFlag)
    {
        if (DATA_SOURCE_NAME == Constants::DB_MYSQL) {

            $this->db->query("
                INSERT INTO ja_2_run_action_table 
                (inner_jobnet_id, inner_job_id, action_flag, status, scheduled_time, created_date, update_date)
                VALUES (:inner_jobnet_id, :inner_job_id, :action_flag, 0, 0, UNIX_TIMESTAMP(), 0)
            ");
        }else {
            $this->db->query("
                INSERT INTO ja_2_run_action_table 
                (inner_jobnet_id, inner_job_id, action_flag, status, scheduled_time, created_date, update_date)
                VALUES (:inner_jobnet_id, :inner_job_id, :action_flag, 0, 0, date_part('epoch'::text, CURRENT_TIMESTAMP), 0)
            ");
        }
        $this->db->bind(':inner_job_id', $innerJobId);
        $this->db->bind(':inner_jobnet_id', $innerJobnetId);
        $this->db->bind(':action_flag', $actionFlag);
        $result = $this->db->execute();
        return $result;
    }

    public function getJobnetSummaryTable(string $innerJobnetId, string $jobnetId)
    {
        $this->db->query("select inner_jobnet_id from ja_2_run_jobnet_summary_table where inner_jobnet_id = :inner_jobnet_id and jobnet_id = :jobnet_id and status = :status");
        $this->db->bind('inner_jobnet_id', $innerJobnetId);
        $this->db->bind('jobnet_id', $jobnetId);
        $this->db->bind('status', Constants::JA_JOBNET_STATUS_RUN);
        $result = $this->db->resultSet();
        return $result;
    }

    public function getInnerJobnetIdAndStartTimeFromJobnetSummary(string $innerJobnetId)
    {
        $this->db->query("SELECT inner_jobnet_id, start_time from ja_2_run_jobnet_summary_table where jobnet_id = :inner_jobnet_id and status = :status");
        $this->db->bind(':inner_jobnet_id', $innerJobnetId);
        $this->db->bind(':status', Constants::JA_JOBNET_STATUS_RUN);
        $result = $this->db->resultSetAsArray();
        return $result;
    }
}
