<?php 

include_once 'version-control.php';


include_once 'master-data.php';

$baseCustomerLabel = $info1000['customer_label'];
$subCustomerLabel = $info3000['subcustomer_label'];
if ($subCustomerLabel === '') {
    $subCustomerLabel = trim('Sub ' . $baseCustomerLabel);
}
if ($subCustomerLabel === '') {
    $subCustomerLabel = 'Sub Customer';
}
$subCustomerPluralLabel = rtrim($subCustomerLabel) . 's';

if (!function_exists('get_sub_customer_label')) {
    function get_sub_customer_label(bool $plural = false): string
    {
        global $subCustomerLabel, $subCustomerPluralLabel;
        return $plural ? $subCustomerPluralLabel : $subCustomerLabel;
    }
}

if (!function_exists('normalize_vendor_note_labels')) {
    function normalize_vendor_note_labels($debitLabel, $creditLabel): array
    {
        $debitLabel = trim((string)$debitLabel);
        $creditLabel = trim((string)$creditLabel);

        if (strcasecmp($debitLabel, 'Credit Note') === 0 && strcasecmp($creditLabel, 'Debit Note') === 0) {
            $tmpLabel = $debitLabel;
            $debitLabel = $creditLabel;
            $creditLabel = $tmpLabel;
        }

        return array(
            'debit' => $debitLabel,
            'credit' => $creditLabel,
        );
    }
}

if (isset($info2000) && is_array($info2000)) {
    $normalizedVendorNoteLabels = normalize_vendor_note_labels(
        $info2000['debitnote_label'] ?? '',
        $info2000['creditnote_label'] ?? ''
    );
    $info2000['debitnote_label'] = $normalizedVendorNoteLabels['debit'];
    $info2000['creditnote_label'] = $normalizedVendorNoteLabels['credit'];
}

if (!function_exists('vendor_debit_note_label')) {
    function vendor_debit_note_label(): string
    {
        global $info2000;
        return (string)($info2000['debitnote_label'] ?? 'Debit Note');
    }
}

if (!function_exists('vendor_credit_note_label')) {
    function vendor_credit_note_label(): string
    {
        global $info2000;
        return (string)($info2000['creditnote_label'] ?? 'Credit Note');
    }
}

if (!function_exists('vendor_debit_note_table')) {
    function vendor_debit_note_table(): string
    {
        static $table = null;
        if ($table === null) {
            $table = (string)mysqli_get_var("SELECT table_label FROM transaction_type WHERE id='11'");
            if ($table === '') {
                $table = 'purchase_credit_note';
            }
        }
        return $table;
    }
}

if (!function_exists('vendor_credit_note_table')) {
    function vendor_credit_note_table(): string
    {
        static $table = null;
        if ($table === null) {
            $table = (string)mysqli_get_var("SELECT table_label FROM transaction_type WHERE id='39'");
            if ($table === '') {
                $table = 'purchase_debit_note';
            }
        }
        return $table;
    }
}

function check_empty($value) {
    return empty($value) ? 0 : $value;
}                                

if (!function_exists('calculate_qty_based_discount_rs')) {
    function calculate_qty_based_discount_rs($productId, $qty)
    {
        $productId = (int)$productId;
        $qty = (float)$qty;

        if ($productId <= 0 || $qty <= 0) {
            return 0;
        }

        $ruleScheme = (float)mysqli_get_var("SELECT discount_percentage FROM amount_discount4 WHERE min_amount='$productId' ORDER BY id DESC LIMIT 1");
        $ruleValue = (float)mysqli_get_var("SELECT discount_value FROM amount_discount4 WHERE min_amount='$productId' ORDER BY id DESC LIMIT 1");

        if ($ruleScheme <= 0 || $ruleValue <= 0) {
            return 0;
        }

        $discountValue = floor($qty / $ruleValue) * $ruleScheme;

        if (!is_finite($discountValue) || $discountValue < 0) {
            return 0;
        }

        return round($discountValue, 4);
    }
}

function format_qty($qty)
{
    if ($qty === null || $qty === '') 
    {
        return 0;
    }

    $qty = (string)$qty;

    if (strpos($qty, '.') !== false) 
    {
        list($int, $dec) = explode('.', $qty, 2);

        if (strlen($dec) > 4) 
        {
            $dec = substr($dec, 0, 4);
        }

        return (float)($int . '.' . $dec);
    }

    return (float)$qty;
}

function indexExistsNew($conn, $table, $indexName) 
{
    // Validate index existence safely
    $result = $conn->query("SHOW INDEX FROM `$table` WHERE Key_name = '$indexName'");
    if (!$result) 
    {
        return false;
    }
    return $result->num_rows > 0;
}

function sortByOrder($a, $b) {
          return $b['total_value'] - $a['total_value'];
        }

if (!function_exists('bill_document_root_dir')) {
    function bill_document_root_dir()
    {
        static $directory = null;
        if ($directory === null) {
            $directory = rtrim(dirname(__DIR__), '/\\') . DIRECTORY_SEPARATOR . 'bill_document';
        }
        return $directory;
    }
}

if (!function_exists('bill_document_ensure_dir')) {
    function bill_document_ensure_dir()
    {
        $dir = bill_document_root_dir();
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }
        return $dir;
    }
}

if (!function_exists('bill_document_paths')) {
    function bill_document_paths($filename)
    {
        $filename = trim((string) $filename);
        $filename = str_replace(['../', '..\\'], '', $filename);
        $filename = ltrim(str_replace('\\', '/', $filename), '/');
        if ($filename === '') {
            $filename = uniqid('file_', true);
        }

        $base = rtrim(bill_document_ensure_dir(), '/\\');
        $disk = $base . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $filename);
        $link = 'bill_document/' . str_replace('\\', '/', $filename);

        return ['disk' => $disk, 'link' => $link];
    }
}

if (!function_exists('bill_document_store_uploaded_file')) {
    function bill_document_store_uploaded_file($filename, $tmpName)
    {
        if (empty($tmpName)) {
            return false;
        }

        $paths = bill_document_paths($filename);
        if (move_uploaded_file($tmpName, $paths['disk'])) {
            return $paths['link'];
        }

        return false;
    }
}

if (!function_exists('bill_document_absolute_path')) {
    function bill_document_absolute_path($link)
    {
        $link = trim((string) $link);
        if ($link === '') {
            return '';
        }

        if (preg_match('#^(?:[A-Za-z]:\\\\|/)#', $link)) {
            return $link;
        }

        $clean = str_replace(['../', '..\\'], '', $link);
        $clean = ltrim(str_replace('\\', '/', $clean), '/');
        $clean = preg_replace('#^bill_document/#i', '', $clean);
        if ($clean === '') {
            return '';
        }

        $base = rtrim(bill_document_root_dir(), '/\\');
        return $base . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $clean);
    }
}

if (!function_exists('bill_document_unlink')) {
    function bill_document_unlink($link)
    {
        $absolute = bill_document_absolute_path($link);
        if ($absolute !== '' && file_exists($absolute)) {
            return unlink($absolute);
        }
        return false;
    }
}

if (!function_exists('resolve_print_href')) {
    function resolve_print_href(string $filename, string $query = ''): string
    {
        $filename = ltrim($filename, '/');
        $query = ltrim($query, '?');
        $suffix = $query !== '' ? '?' . $query : '';

        $scriptFile = $_SERVER['SCRIPT_FILENAME'] ?? '';
        $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
        if ($scriptFile !== '' && $scriptName !== '') {
            $scriptDir = rtrim(str_replace('\\', '/', dirname($scriptFile)), '/');
            if (is_file($scriptDir . '/' . $filename)) {
                $scriptDirUrl = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
                return $scriptDirUrl . '/' . $filename . $suffix;
            }
        }

        $docRootPath = rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT'] ?? ''), '/');
        $appRootPath = rtrim(str_replace('\\', '/', dirname(__DIR__)), '/');
        $relativeAppPath = '';
        if ($docRootPath !== '' && strpos($appRootPath, $docRootPath) === 0) {
            $relativeAppPath = substr($appRootPath, strlen($docRootPath));
        }
        $relativeAppPath = '/' . ltrim($relativeAppPath, '/');

        $candidateDirs = ['treasury', 'sales', 'purchase'];
        foreach ($candidateDirs as $dir) {
            $fsPath = $appRootPath . '/' . $dir . '/' . $filename;
            if (is_file($fsPath)) {
                return $relativeAppPath . '/' . $dir . '/' . $filename . $suffix;
            }
        }

        if (!empty($GLOBALS['info1000']['printview_slug'])) {
            return rtrim($GLOBALS['info1000']['printview_slug'], '/') . '/' . $filename . $suffix;
        }

        return $filename . $suffix;
    }
}

if (!function_exists('sync_quotation_attachment_count')) {
    function sync_quotation_attachment_count($conn, $refId)
    {
        $refId = (int) $refId;
        if ($refId <= 0) {
            return 0;
        }

        $count = 0;
        $countResult = mysqli_query($conn, "SELECT COUNT(*) AS total FROM files_attached WHERE ref='$refId' AND type=100");
        if ($countResult instanceof mysqli_result) {
            $row = mysqli_fetch_assoc($countResult);
            if ($row && isset($row['total'])) {
                $count = (int) $row['total'];
            }
            mysqli_free_result($countResult);
        }

        mysqli_query($conn, "UPDATE lead_quotation SET files_attached = $count WHERE lq_id='$refId'") or die(mysqli_error($conn));
        return $count;
    }
}

if (!function_exists('save_quotation_attachments')) {
    /**
     * Stores uploaded quotation files into files_attached and increments the counter.
     *
     * @param mysqli $conn
     * @param int $refId Lead quotation ID
     * @param string $fileField
     * @param string $nameField
     * @param string $remarksField
     * @return int Number of files saved
     */
    function save_quotation_attachments($conn, $refId, $fileField = 'attachment_file', $nameField = 'attachment_name', $remarksField = 'attachment_remarks')
    {
        $refId = (int) $refId;
        if ($refId <= 0) {
            return 0;
        }
        if (
            !isset($_FILES[$fileField]['name']) ||
            !is_array($_FILES[$fileField]['name'])
        ) {
            return 0;
        }

        $fileData = $_FILES[$fileField];
        $nameInputs = isset($_POST[$nameField]) && is_array($_POST[$nameField]) ? $_POST[$nameField] : [];
        $remarkInputs = isset($_POST[$remarksField]) && is_array($_POST[$remarksField]) ? $_POST[$remarksField] : [];
        $savedCount = 0;
        $total = count($fileData['name']);
        $errors = isset($fileData['error']) ? $fileData['error'] : [];

        for ($i = 0; $i < $total; $i++) {
            $original = isset($fileData['name'][$i]) ? trim((string) $fileData['name'][$i]) : '';
            $tmpName = isset($fileData['tmp_name'][$i]) ? $fileData['tmp_name'][$i] : '';
            $errorCode = isset($errors[$i]) ? (int) $errors[$i] : UPLOAD_ERR_OK;
            if ($original === '' || $tmpName === '' || $errorCode !== UPLOAD_ERR_OK || !is_uploaded_file($tmpName)) {
                continue;
            }

            $displayName = isset($nameInputs[$i]) ? test_input($nameInputs[$i]) : '';
            if ($displayName === '') {
                $displayName = $original;
            }
            $remarks = isset($remarkInputs[$i]) ? test_input($remarkInputs[$i]) : '';
            $date = date("Y-m-d H:i:s");

            $insertSql = "INSERT INTO files_attached (`file_name`, `ref`, `type`, `remarks`, `datetime`) VALUES ('" . mysqli_real_escape_string($conn, $displayName) . "', '$refId', '100', '" . mysqli_real_escape_string($conn, $remarks) . "', '$date')";
            if (!mysqli_query($conn, $insertSql)) {
                continue;
            }

            $recordId = mysqli_insert_id($conn);
            $mimeType = isset($fileData['type'][$i]) ? $fileData['type'][$i] : '';
            $ext = GetImageExtension2($mimeType);
            if ($ext === false || $ext === '') {
                $origExt = pathinfo($original, PATHINFO_EXTENSION);
                $ext = $origExt ? '.' . strtolower($origExt) : '';
            }
            $filename = $recordId . "_quotationdoc" . $ext;
            $target_path = "bill_document/" . $filename;

            $savedLink = bill_document_store_uploaded_file(basename($target_path), $tmpName);
            if ($savedLink) {
                mysqli_query($conn, "UPDATE files_attached SET link='" . mysqli_real_escape_string($conn, $savedLink) . "' WHERE id='$recordId'");
                $savedCount++;
            } else {
                mysqli_query($conn, "DELETE FROM files_attached WHERE id='$recordId'");
            }
        }

        if ($savedCount > 0) {
            sync_quotation_attachment_count($conn, $refId);
        }

        return $savedCount;
    }
}


if (!function_exists('is_attendance_punching_enabled')) {
    function is_attendance_punching_enabled(): bool
    {
        global $info1000, $info2000;

        $hrEnabled = isset($info1000['en_employee']) && (int) $info1000['en_employee'] === 1;
        if (!$hrEnabled) {
            return false;
        }

        $attendanceToggles = [
            $info2000['en_new_hr'] ?? null,
            $info2000['en_simple_hr'] ?? null,
            $info2000['system_hrrequest'] ?? null,
        ];

        $attendanceEnabled = false;
        foreach ($attendanceToggles as $toggle) {
            if ($toggle !== null && (int) $toggle === 1) {
                $attendanceEnabled = true;
                break;
            }
        }

        if (!$attendanceEnabled) {
            return false;
        }

        if (isset($info2000['attendance_format']) && (int) $info2000['attendance_format'] === 0) {
            return false;
        }

        return true;
    }
}


      function primaryKeyExists($conn, $tableName) {
    $result = mysqli_query($conn, "SHOW INDEX FROM `$tableName` WHERE Key_name = 'PRIMARY'") or die(mysqli_error($conn));
    return (mysqli_num_rows($result) > 0);
}  


function mysqli_get_var($query, $y = 0){
  global $conn;

  if (function_exists('optimize_cash_transaction_datetime_filters')) {
      $query = optimize_cash_transaction_datetime_filters($query);
  }

  try {
      $res = mysqli_query($conn, $query);
  } catch (mysqli_sql_exception $e) {
      $sqlErrorCode = (int)$e->getCode();
      if ($sqlErrorCode === 1054 || $sqlErrorCode === 1146) {
          return null;
      }
      throw $e;
  }

  if($res === false){
      $sqlErrorCode = (int)mysqli_errno($conn);
      if ($sqlErrorCode === 1054 || $sqlErrorCode === 1146) {
          return null;
      }
      return null;
  }

  $row = mysqli_fetch_array($res);
  mysqli_free_result($res);

  if(!$row){
      return null;
  }

  if(is_string($y)){
      return array_key_exists($y, $row) ? $row[$y] : null;
  }

  $keys = array_keys($row);
  if(is_int($y) && isset($keys[$y])){
      return $row[$keys[$y]];
  }

  return null;
}

if (!function_exists('master_data_load_table')) {
    function master_data_load_table($table)
    {
        global $conn, $master_data, $master_data_config, $master_data_loaded;

        if (!is_string($table) || $table === '') {
            return false;
        }

        if (isset($master_data_loaded[$table])) {
            return $master_data_loaded[$table] ? true : false;
        }

        if (!isset($master_data_config[$table]) || !is_array($master_data_config[$table])) {
            $master_data_loaded[$table] = false;
            return false;
        }

        $columns = array_values(array_unique($master_data_config[$table]));
        if (count($columns) === 0) {
            $master_data_loaded[$table] = false;
            return false;
        }

        if (master_data_cache_enabled()) {
            $cache_key = master_data_cache_key($table, $columns);
            $cached = apcu_fetch($cache_key, $cache_hit);
            if ($cache_hit && is_array($cached)) {
                $master_data[$table] = $cached;
                $master_data_loaded[$table] = true;
                return true;
            }
        }

        $cols_sql = '`' . implode('`, `', $columns) . '`';
        $sql = "SELECT id, $cols_sql FROM `$table`";
        $res = mysqli_query($conn, $sql);
        if ($res === false) {
            $master_data_loaded[$table] = false;
            return false;
        }

        $master_data[$table] = array();
        while ($row = mysqli_fetch_assoc($res)) {
            $id = $row['id'];
            foreach ($columns as $column) {
                $master_data[$table][$id][$column] = $row[$column];
            }
        }

        mysqli_free_result($res);
        if (master_data_cache_enabled()) {
            apcu_store($cache_key, $master_data[$table], master_data_cache_ttl());
        }
        $master_data_loaded[$table] = true;
        return true;
    }
}

if (!function_exists('master_data_cache_enabled')) {
    function master_data_cache_enabled()
    {
        if (!function_exists('apcu_fetch')) {
            return false;
        }
        $enabled = ini_get('apc.enabled');
        if ($enabled === '' || $enabled === false) {
            return true;
        }
        return ((int) $enabled === 1);
    }
}

if (!function_exists('master_data_cache_ttl')) {
    function master_data_cache_ttl()
    {
        if (defined('MASTER_DATA_CACHE_TTL')) {
            return max(0, (int) MASTER_DATA_CACHE_TTL);
        }
        return 300;
    }
}

if (!function_exists('master_data_cache_key')) {
    function master_data_cache_key($table, array $columns)
    {
        $column_hash = md5(implode(',', $columns));
        return 'bms_master_data_' . $table . '_' . $column_hash;
    }
}

if (!function_exists('master_data_cache_clear')) {
    function master_data_cache_clear($table = null)
    {
        global $master_data_config;

        if (!master_data_cache_enabled()) {
            return false;
        }

        if ($table === null) {
            if (!is_array($master_data_config)) {
                return false;
            }
            foreach ($master_data_config as $table_name => $columns) {
                if (!is_array($columns) || count($columns) === 0) {
                    continue;
                }
                $columns = array_values(array_unique($columns));
                apcu_delete(master_data_cache_key($table_name, $columns));
            }
            apcu_delete('bms_master_data_system_pages');
            return true;
        }

        if ($table === 'system_pages') {
            return apcu_delete('bms_master_data_system_pages');
        }

        if (!isset($master_data_config[$table]) || !is_array($master_data_config[$table])) {
            return false;
        }

        $columns = array_values(array_unique($master_data_config[$table]));
        if (count($columns) === 0) {
            return false;
        }

        return apcu_delete(master_data_cache_key($table, $columns));
    }
}

if (!function_exists('master_data_cache_auto_clear_on_write_request')) {
    function master_data_cache_auto_clear_on_write_request()
    {
        static $registered = false;
        if ($registered) {
            return;
        }
        $registered = true;

        if (!master_data_cache_enabled()) {
            return;
        }
        if (defined('MASTER_DATA_CACHE_AUTOCLEAR') && !MASTER_DATA_CACHE_AUTOCLEAR) {
            return;
        }

        $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : '';
        $write_methods = array('POST', 'PUT', 'PATCH', 'DELETE');
        $has_payload = !empty($_POST) || !empty($_FILES);

        if ($has_payload || ($method !== '' && in_array($method, $write_methods, true))) {
            register_shutdown_function('master_data_cache_clear');
        }
    }
}
master_data_cache_auto_clear_on_write_request();

if (!function_exists('master_get_var')) {
    function master_get_var($query, $y = 0)
    {
        global $master_data;

        if (!is_string($query)) {
            return mysqli_get_var($query, $y);
        }

        $query_trim = trim($query);
        if ($query_trim === '') {
            return mysqli_get_var($query, $y);
        }

        if (!preg_match('/^\\s*select\\s+/i', $query_trim)) {
            return mysqli_get_var($query, $y);
        }

        $pattern = '/^\\s*select\\s+(`?[a-zA-Z0-9_]+`?(?:\\s+as\\s+`?[a-zA-Z0-9_]+`?)?)\\s+from\\s+`?([a-zA-Z0-9_]+)`?\\s+where\\s+`?id`?\\s*=\\s*(?:\\\'([^\\\']*)\\\'|\"([^\"]*)\"|([0-9]+))\\s*;?\\s*(?:limit\\s+\\d+\\s*)?$/i';
        if (preg_match($pattern, $query_trim, $matches)) {
            $column_expr = $matches[1];
            $table = strtolower($matches[2]);
            $id = $matches[3] !== '' ? $matches[3] : ($matches[4] !== '' ? $matches[4] : $matches[5]);

            $column_expr = preg_replace('/\\s+as\\s+.*$/i', '', $column_expr);
            $column = trim($column_expr, " `\t\n\r\0\x0B");

            if ($column !== '' && master_data_load_table($table)) {
                if (isset($master_data[$table]) && isset($master_data[$table][$id]) && array_key_exists($column, $master_data[$table][$id])) {
                    return $master_data[$table][$id][$column];
                }
            }
        }

        return mysqli_get_var($query, $y);
    }
}

if (!function_exists('optimize_cash_transaction_datetime_filters')) {
    function optimize_cash_transaction_datetime_filters($query)
    {
        if (!is_string($query) || $query === '') {
            return $query;
        }

        $query = preg_replace_callback(
            '/MONTH\\(\\s*c\\.datetime\\s*\\)\\s*=\\s*MONTH\\(\\s*\\\'([^\\\']+)\\\'\\s*\\)\\s*(?:AND|&&)\\s*YEAR\\(\\s*c\\.datetime\\s*\\)\\s*=\\s*YEAR\\(\\s*\\\'([^\\\']+)\\\'\\s*\\)/i',
            function ($matches) {
                $timestamp = strtotime($matches[1]);
                if ($timestamp === false) {
                    return $matches[0];
                }

                $start = date('Y-m-01 00:00:00', $timestamp);
                $end = date('Y-m-01 00:00:00', strtotime('+1 month', $timestamp));
                return "c.datetime >= '$start' AND c.datetime < '$end'";
            },
            $query
        );

        $query = preg_replace_callback(
            '/YEAR\\(\\s*c\\.datetime\\s*\\)\\s*=\\s*YEAR\\(\\s*\\\'([^\\\']+)\\\'\\s*\\)/i',
            function ($matches) {
                $timestamp = strtotime($matches[1]);
                if ($timestamp === false) {
                    return $matches[0];
                }

                $start = date('Y-01-01 00:00:00', $timestamp);
                $end = date('Y-01-01 00:00:00', strtotime('+1 year', $timestamp));
                return "c.datetime >= '$start' AND c.datetime < '$end'";
            },
            $query
        );

        $query = preg_replace_callback(
            '/DATE\\(\\s*c\\.datetime\\s*\\)\\s*>=\\s*DATE\\(\\s*\\\'([^\\\']+)\\\'\\s*\\)\\s*(?:AND|&&)\\s*DATE\\(\\s*c\\.datetime\\s*\\)\\s*<=\\s*DATE\\(\\s*\\\'([^\\\']+)\\\'\\s*\\)/i',
            function ($matches) {
                $startTs = strtotime($matches[1]);
                $endTs = strtotime($matches[2]);
                if ($startTs === false || $endTs === false) {
                    return $matches[0];
                }

                $start = date('Y-m-d 00:00:00', $startTs);
                $end = date('Y-m-d 00:00:00', strtotime('+1 day', $endTs));
                return "c.datetime >= '$start' AND c.datetime < '$end'";
            },
            $query
        );

        $query = preg_replace_callback(
            '/DATE\\(\\s*c\\.datetime\\s*\\)\\s*=\\s*DATE\\(\\s*\\\'([^\\\']+)\\\'\\s*\\)/i',
            function ($matches) {
                $timestamp = strtotime($matches[1]);
                if ($timestamp === false) {
                    return $matches[0];
                }

                $start = date('Y-m-d 00:00:00', $timestamp);
                $end = date('Y-m-d 00:00:00', strtotime('+1 day', $timestamp));
                return "c.datetime >= '$start' AND c.datetime < '$end'";
            },
            $query
        );

        return $query;
    }
}

if (!function_exists('get_master_pos_discount')) {
    /**
     * Resolve the active POS master discount for a product.
     *
     * @param int         $productId Target inventory id.
     * @param int         $brandId   Product brand id.
     * @param int         $typeId    Product category id.
     * @param int         $subtypeId Product sub category id.
     * @param int         $companyId Current company context.
     * @param string|null $onDate    Date to evaluate (Y-m-d), defaults to current date.
     *
     * @return array{percentage: ?float, amount: ?float}
     */
    function get_master_pos_discount(
        int $productId,
        int $brandId = 0,
        int $typeId = 0,
        int $subtypeId = 0,
        int $companyId = 0,
        ?string $onDate = null
    ): array {
        global $conn;

        static $cache = [];

        if ($productId <= 0 || !$conn) {
            return ['percentage' => null, 'amount' => null];
        }

        $brandId = max(0, $brandId);
        $typeId = max(0, $typeId);
        $subtypeId = max(0, $subtypeId);
        $companyId = max(0, $companyId);

        if ($onDate === null) {
            $onDate = date('Y-m-d');
        }

        $cacheKey = implode('|', [$productId, $brandId, $typeId, $subtypeId, $companyId, $onDate]);
        if (isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }

        $safeDate = mysqli_real_escape_string($conn, $onDate);

        $query = "
            SELECT
                discount_percentage,
                discount_amount,
                (
                    (CASE WHEN product_id IS NOT NULL AND product_id != 0 AND product_id = $productId THEN 8 ELSE 0 END) +
                    (CASE WHEN subtype_id IS NOT NULL AND subtype_id != 0 AND subtype_id = $subtypeId THEN 4 ELSE 0 END) +
                    (CASE WHEN type_id IS NOT NULL AND type_id != 0 AND type_id = $typeId THEN 2 ELSE 0 END) +
                    (CASE WHEN brand_id IS NOT NULL AND brand_id != 0 AND brand_id = $brandId THEN 1 ELSE 0 END)
                ) AS priority
            FROM pos_master_discount
            WHERE (company_id = $companyId OR company_id = 0)
              AND (product_id IS NULL OR product_id = 0 OR product_id = $productId)
              AND (brand_id IS NULL OR brand_id = 0 OR brand_id = $brandId)
              AND (type_id IS NULL OR type_id = 0 OR type_id = $typeId)
              AND (subtype_id IS NULL OR subtype_id = 0 OR subtype_id = $subtypeId)
              AND (start_date IS NULL OR start_date = '0000-00-00' OR start_date <= '$safeDate')
              AND (end_date IS NULL OR end_date = '0000-00-00' OR end_date >= '$safeDate')
            ORDER BY priority DESC,
                     product_id DESC,
                     subtype_id DESC,
                     type_id DESC,
                     brand_id DESC,
                     start_date DESC,
                     id DESC
            LIMIT 1
        ";

        $result = mysqli_query($conn, $query) or die(mysqli_error($conn));
        $row = mysqli_fetch_assoc($result);
        mysqli_free_result($result);

        if ($row) {
            $cache[$cacheKey] = [
                'percentage' => $row['discount_percentage'] !== null ? (float) $row['discount_percentage'] : null,
                'amount' => $row['discount_amount'] !== null ? (float) $row['discount_amount'] : null,
            ];
        } else {
            $cache[$cacheKey] = ['percentage' => null, 'amount' => null];
        }

        return $cache[$cacheKey];
    }
}


$pagescompany = $info1000['id'];


function get_system_pages_index_state()
{
    global $conn;

    $state = [
        'has_company_scope_key' => false,
        'primary_id_only' => false,
        'unique_id_only' => []
    ];

    $result = mysqli_query($conn, "SHOW INDEX FROM system_pages");
    if (!$result) {
        return $state;
    }

    $indexes = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $keyName = $row['Key_name'];
        if (!isset($indexes[$keyName])) {
            $indexes[$keyName] = [
                'non_unique' => (int)$row['Non_unique'],
                'columns' => []
            ];
        }
        $indexes[$keyName]['columns'][(int)$row['Seq_in_index']] = $row['Column_name'];
    }
    mysqli_free_result($result);

    foreach ($indexes as $keyName => $indexMeta) {
        if ((int)$indexMeta['non_unique'] !== 0) {
            continue;
        }

        ksort($indexMeta['columns']);
        $columns = array_values($indexMeta['columns']);

        if (
            count($columns) === 2 &&
            in_array('id', $columns, true) &&
            in_array('company_id', $columns, true)
        ) {
            $state['has_company_scope_key'] = true;
        }

        if (count($columns) === 1 && $columns[0] === 'id') {
            if ($keyName === 'PRIMARY') {
                $state['primary_id_only'] = true;
            } else {
                $state['unique_id_only'][] = $keyName;
            }
        }
    }

    return $state;
}

function ensure_system_pages_company_scope()
{
    global $conn;
    static $isReady = null;

    if ($isReady !== null) {
        return $isReady;
    }

    $state = get_system_pages_index_state();
    if ($state['has_company_scope_key'] && !$state['primary_id_only'] && empty($state['unique_id_only'])) {
        $isReady = true;
        return true;
    }

    if ($state['primary_id_only']) {
        mysqli_query($conn, "ALTER TABLE system_pages DROP PRIMARY KEY, ADD PRIMARY KEY (`id`, `company_id`)");
    }

    if (!empty($state['unique_id_only'])) {
        foreach ($state['unique_id_only'] as $keyName) {
            $safeKeyName = str_replace('`', '``', $keyName);
            mysqli_query($conn, "ALTER TABLE system_pages DROP INDEX `$safeKeyName`");
        }
    }

    $state = get_system_pages_index_state();
    if (!$state['has_company_scope_key']) {
        mysqli_query($conn, "ALTER TABLE system_pages ADD UNIQUE KEY `uq_system_pages_id_company` (`id`, `company_id`)");
    }

    $state = get_system_pages_index_state();
    $isReady = ($state['has_company_scope_key'] && !$state['primary_id_only'] && empty($state['unique_id_only']));
    return $isReady;
}


function initiate_pages(){
  
     
       global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
       $companyScopeReady = ensure_system_pages_company_scope();
 
 


   $query ="DROP TEMPORARY TABLE IF EXISTS temp_system_pages";
    $retval = mysqli_query($conn, $query ) or die(mysqli_error($conn) );

  
   $query ="CREATE TEMPORARY TABLE temp_system_pages LIKE system_pages";
$retval = mysqli_query($conn, $query ) or die(mysqli_error($conn) );




$sql = " INSERT INTO `temp_system_pages` (`id`, `page_label`, `access_heirarchy`, `parent`, `enable`, `type`, `link`, `log_link`, `log_name`) VALUES
(1, 'Dashboard', 1, 0, 1, 1, 'dashboard/index.php', '#', 'Logged In'),
(2, 'Product', 1, 0, 1, 1, 'NULL', NULL, NULL),
(3, 'Raw Material', 1, 0, 1, 12, 'NULL', NULL, NULL),
(4, 'Customer', 1, 0, 1, 1, 'NULL', NULL, NULL),
(5, 'Vendor', 1, 0, 1, 1, 'NULL', NULL, NULL),
(6, 'Warehouse', 1, 0, 1, 1, 'NULL', NULL, NULL),
(7, 'Sales', 1, 0, 1, 1, 'NULL', NULL, NULL),
(8, 'Purchasing', 1, 0, 1, 1, 'NULL', NULL, NULL),
(9, 'Expenses', 1, 0, 1, 1, 'NULL', NULL, NULL),
(10, 'Import &amp; Export ', 1, 0, 0, 6, 'NULL', NULL, NULL),
(11, 'Production', 1, 0, 1, 8, 'NULL', NULL, NULL),
(12, 'CRM', 1, 0, 1, 7, 'NULL', NULL, NULL),
(13, 'Settings', 1, 0, 1, 1, 'NULL', NULL, NULL),
(14, 'Approvals', 1, 0, 1, 1, 'NULL', NULL, NULL),
(15, 'Treasury', 1, 0, 1, 1, 'NULL', NULL, NULL),
(16, 'Accounts', 1, 0, 1, 1, 'finance/index.php', NULL, NULL),
(17, 'Report Center', 1, 0, 1, 1, 'reports/index.php', NULL, NULL),
(18, 'Human Resources', 1, 0, 1, 9, 'NULL', NULL, NULL),
(19, 'Attendance Management', 1, 0, 1, 9, 'NULL', NULL, NULL),
(20, 'Employee Registration', 1, 0, 1, 9, 'new-employee-out.php', NULL, NULL),
(21, 'BA', 1, 0, 0, 4, 'NULL', NULL, NULL),
(22, 'LP Claim Status', 1, 0, 0, 5, 'NULL', NULL, NULL),
(23, 'IMEI Status', 1, 0, 0, 5, 'NULL', NULL, NULL),
(24, 'Order Booker / Salesman', 1, 0, 1, 2, 'NULL', NULL, NULL),
(31, 'Distributor (SND / Call Report)', 1, 0, 0, 2, 'NULL', NULL, NULL),
(32, 'Merchandising (SND / Call Report)', 1, 0, 0, 2, 'NULL', NULL, NULL),
(33, 'Support (SND / Call Report)', 1, 0, 0, 2, 'NULL', NULL, NULL),
(34, 'Routes (SND / Call Report)', 1, 0, 0, 2, 'NULL', NULL, NULL),
(35, 'Territory Builder (SND / Call Report)', 1, 0, 0, 2, 'NULL', NULL, NULL),
(36, 'Products (SND / Call Report)', 1, 0, 0, 2, 'NULL', NULL, NULL),
(25, 'Order Delivery', 1, 0, 0, 2, 'NULL', NULL, NULL),
(26, 'Bill Printing', 1, 0, 0, 2, 'tso-bill-print.php', NULL, NULL),
(27, 'Execution', 1, 0, 0, 2, 'NULL', NULL, NULL),
(28, 'Route Finalize', 1, 0, 0, 2, 'NULL', NULL, NULL),
(29, 'KPO', 1, 0, 0, 2, 'NULL', NULL, NULL),
(30, 'Stock Management', 1, 0, 0, 2, 'NULL', NULL, NULL),
(38, 'Doctors', 1, 0, 0, 3, 'NULL', NULL, NULL),
(39, 'Pharmacy', 1, 0, 0, 3, 'NULL', NULL, NULL),
(40, 'Expenses', 1, 0, 0, 3, 'NULL', NULL, NULL),
(41, 'Demo Plot Reporting', 1, 0, 0, 3, 'NULL', NULL, NULL),
(42, 'Activity', 1, 0, 0, 3, 'NULL', NULL, NULL),
(43, 'Quizes', 1, 0, 0, 3, 'NULL', NULL, NULL),
(37, 'Medical Representatives', 1, 0, 0, 3, 'NULL', NULL, NULL),
(44, 'Accounts Reports', 3, 16, 1, 1, '#', NULL, NULL),
(45, 'Cost Center', 2, 16, 1, 1, 'NULL', NULL, NULL),
(46, 'General Actions', 2, 16, 1, 1, 'NULL', NULL, NULL),
(47, 'Chart of Account', 2, 16, 1, 1, 'NULL', NULL, NULL),
(48, 'Create Cost Center', 3, 45, 1, 1, 'create-cost-center.php', NULL, NULL),
(49, 'Manage Cost Center', 3, 45, 1, 1, 'manage-cost-center.php', NULL, NULL),
(50, 'General Ledger', 3, 44, 1, 1, 'ledger-view.php', NULL, NULL),
(51, 'Trial Balance', 3, 44, 1, 1, 'trial-balance.php', NULL, NULL),
(52, 'Trial Balance (Detailed)', 3, 44, 1, 1, 'trial-balance2.php', NULL, NULL),
(53, 'Balance Sheet', 3, 44, 1, 1, 'balance-sheet.php', NULL, NULL),
(54, 'Profit &amp; Loss Statement', 3, 44, 1, 1, 'report-profit-report.php', NULL, NULL),
(55, 'General Journal', 3, 44, 1, 1, 'general-journal.php', NULL, NULL),
(56, 'Daily Financial Position', 3, 44, 1, 1, 'daily-financial-position.php', NULL, NULL),
(57, 'Bank Reconciliation Position', 3, 44, 1, 1, 'daily-bank-position.php', NULL, NULL),
(58, 'Customer / Dealer Ledger', 3, 44, 1, 1, 'customer-ledger.php', NULL, NULL),
(59, 'Vendor Ledger', 3, 44, 1, 1, 'vendor-ledger.php', NULL, NULL),
(60, 'Expense Vendor Ledger', 3, 44, 1, 1, 'NULL', NULL, NULL),
(61, 'Receipt Register', 3, 44, 1, 1, 'report-receipt-register.php', NULL, NULL),
(62, 'Receipt Register (Bank Wise)', 3, 44, 1, 1, 'report-receipt-register2.php', NULL, NULL),
(63, 'Payment Register', 3, 44, 1, 1, 'report-payment-register.php', NULL, NULL),
(64, 'Payment Register (Bank Wise)', 3, 44, 1, 1, 'report-payment-register2.php', NULL, NULL),
(65, 'Receipt Summary', 3, 44, 1, 1, 'report-receipt-summary.php', NULL, NULL),
(66, 'Payment Summary', 0, 44, 1, 1, 'report-payment-summary.php', NULL, NULL),
(67, 'Aging Report', 3, 44, 1, 1, 'c-aging-report.php', NULL, NULL),
(68, 'Aging Payable', 3, 44, 1, 1, 'v-aging-report.php', NULL, NULL),
(69, 'Customer Credit Report', 3, 44, 1, 1, 'c-credit-report.php', NULL, NULL),
(70, 'Customer Sales / Payment', 3, 44, 1, 1, 'report-sp-details.php', NULL, NULL),
(71, 'Cost Center Report', 3, 44, 1, 1, 'report-cost-center.php', NULL, NULL),
(72, 'Customer Activty', 3, 44, 1, 1, 'report-customer-activity.php', NULL, NULL),
(73, 'Vendor Activity', 3, 44, 1, 1, 'report-vendor-activity.php', NULL, NULL),
(74, 'Customer Balance Summary Report', 3, 44, 1, 1, 'c-balance-report.php', NULL, NULL),
(75, 'Vendor Balance Summary Report', 3, 44, 1, 1, 'v-balance-report.php', NULL, NULL),
(76, 'Transfer Funds', 3, 46, 1, 1, 'transfer-funds.php', NULL, NULL),
(77, 'New General Journal Entries', 3, 46, 1, 1, 'general-journal-entries.php', NULL, NULL),
(78, 'Manage General Journal Entries', 3, 46, 1, 1, 'manage-general-journal.php', NULL, NULL),
(79, 'Bank Reconciliation', 3, 46, 1, 1, 'bank-reconciliation.php', NULL, NULL),
(80, 'Manage Bank Reconciliation', 3, 46, 1, 1, 'manage-bank-reconciliation.php', NULL, NULL),
(81, 'Inport Outstanding Invoices Sales', 3, 46, 1, 1, 'import-outstanding-invoices.php', NULL, NULL),
(82, 'Pay Sales Tax', 3, 46, 1, 1, 'pay-sales-tax.php', NULL, NULL),
(83, 'Drawing', 3, 46, 1, 1, 'drawing.php', NULL, NULL),
(84, 'Further Investment', 3, 46, 1, 1, 'further-investment.php', NULL, NULL),
(85, 'Closing', 3, 46, 1, 1, 'closing.php', NULL, NULL),
(86, 'Perform Asset Depreciation', 3, 1532, 1, 15, 'asset-depreciation.php', NULL, NULL),
(87, 'Create Account (Level 1)', 3, 46, 1, 1, 'create-account-type1.php', NULL, NULL),
(88, 'Manage Account (Level 1)', 3, 46, 1, 1, 'manage-account-type1.php', NULL, NULL),
(89, 'Create Account (Level 2)', 3, 46, 1, 1, 'create-account-type2.php', NULL, NULL),
(90, 'Manage Account (Level 2)', 3, 46, 1, 1, 'manage-account-type2.php', NULL, NULL),
(91, 'Create Account (Level 3)', 3, 46, 1, 1, 'create-account-type.php', NULL, NULL),
(92, 'Manage Account (Level 3)', 3, 46, 1, 1, 'manage-account-type.php', NULL, NULL),
(93, 'Create Account (Level 4)', 3, 46, 1, 1, 'create-account.php', NULL, NULL),
(94, 'Manage Account (Level 4)', 3, 46, 1, 1, 'manage-account.php', NULL, NULL),
(95, 'Manage Account Code (Level 4)', 3, 46, 1, 1, 'manage-account-code.php', NULL, NULL),
(96, 'Expense Payments', 2, 15, 1, 1, 'NULL', NULL, NULL),
(97, 'Sales Receipts', 2, 15, 1, 1, 'NULL', NULL, NULL),
(98, 'Purchase Payments', 2, 15, 1, 1, 'NULL', NULL, NULL),
(99, 'General Payments', 2, 15, 1, 1, 'NULL', NULL, NULL),
(100, 'Journal Voucher', 2, 15, 1, 1, 'NULL', NULL, NULL),
(101, 'Payroll Liabilities', 2, 15, 1, 1, 'NULL', NULL, NULL),
(102, 'Payment Voucher', 3, 96, 1, 1, 'ppayment-voucher.php', NULL, NULL),
(103, 'Manage Payments', 3, 96, 1, 1, 'purchase-payment-receipts.php', NULL, NULL),
(104, 'Receipt Voucher', 3, 97, 1, 1, 'spayment-voucher.php', NULL, NULL),
(105, 'Manage Sales Receipts', 3, 97, 1, 1, 'sales-payment-receipts.php', NULL, NULL),
(106, 'Care of List', 3, 97, 1, 1, 'ccareof-list.php', NULL, NULL),
(107, 'Cheque Clearing', 3, 97, 1, 1, 'ccheque_clearing.php', NULL, NULL),
(108, 'Cheque Returned', 3, 97, 1, 1, 'ccheque_return.php', NULL, NULL),
(109, 'Payment Voucher', 3, 98, 1, 1, 'ppayment-voucher.php', NULL, NULL),
(110, 'Purchase Payment Vouchers', 3, 98, 1, 1, 'purchase-payment-receipts.php', NULL, NULL),
(111, 'Care of List', 3, 98, 1, 1, 'pcareof-list.php', NULL, NULL),
(112, 'Cheque Clearing', 3, 98, 1, 1, 'vcheque_clearing.php', NULL, NULL),
(113, 'Cheque Returned', 3, 98, 1, 1, 'vcheque_return.php', NULL, NULL),
(114, 'New Payment Voucher', 3, 99, 1, 1, 'gppayment-voucher.php', NULL, NULL),
(115, 'Manage General Payments', 3, 99, 1, 1, 'general-payment-vouchers.php', NULL, NULL),
(116, 'New Receipt Voucher', 3, 99, 1, 1, 'grpayment-voucher.php', NULL, NULL),
(117, 'Manage General Receipts', 3, 99, 1, 1, 'general-receipts-vouchers.php', NULL, NULL),
(118, 'New  General Journal Entries', 3, 100, 1, 1, 'general-journal-entries.php', NULL, NULL),
(119, 'Manage General Journal Entries', 3, 100, 1, 1, 'manage-general-journal.php', NULL, NULL),
(120, 'Payroll Payable', 3, 101, 1, 9, 'payroll-payable.php', NULL, NULL),
(121, 'Manage Payroll List', 3, 101, 1, 9, 'manage-payroll-list.php', NULL, NULL),
(122, 'Import Advice', 2, 10, 0, 6, 'NULL', NULL, NULL),
(123, 'Duties &amp; Taxes', 2, 10, 0, 6, 'NULL', NULL, NULL),
(124, 'Other Fees', 2, 10, 0, 6, 'NULL', NULL, NULL),
(125, 'New Import', 3, 122, 0, 6, 'NULL', NULL, NULL),
(126, 'Manage Import', 3, 122, 0, 6, 'NULL', NULL, NULL),
(127, 'New Duty', 3, 123, 0, 6, 'NULL', NULL, NULL),
(128, 'Manage Duties', 3, 123, 0, 6, 'NULL', NULL, NULL),
(129, 'New Fees', 3, 124, 0, 6, 'NULL', NULL, NULL),
(130, 'Manage Fees', 3, 124, 0, 6, 'NULL', NULL, NULL),
(131, 'New Sales', 2, 7, 1, 1, 'new-sales-receipt.php', NULL, NULL),
(132, 'New Return', 2, 7, 1, 1, 'new-return-receipt.php', NULL, NULL),
(133, 'Pending SO', 2, 7, 1, 1, 'manage-pending-tso2.php', NULL, NULL),
(134, 'Pending SR Request', 2, 7, 1, 1, 'manage-pending-tso-return2.php', NULL, NULL),
(135, 'Pending Sale Invoice', 2, 7, 1, 1, 'manage-pending-gso.php', NULL, NULL),
(136, 'Pending Sale Return Invoice', 2, 7, 1, 1, 'manage-pending-rgso.php', NULL, NULL),
(137, 'Pending Inventory', 2, 7, 1, 1, 'NULL', NULL, NULL),
(138, 'Pending Sale Orders', 2, 7, 1, 1, 'manage-pending-so.php', NULL, NULL),
(139, 'Pending Sale Return', 2, 7, 1, 1, 'manage-pending-tso-return.php', NULL, NULL),
(140, 'Sales Orders', 2, 7, 1, 1, 'manage-so.php', NULL, NULL),
(141, 'Sales Invoices', 2, 7, 1, 1, 'manage-sales.php', NULL, NULL),
(142, 'Recurring Sales Invoices', 2, 7, 1, 1, 'NULL', NULL, NULL),
(143, 'New Purchase Requisition', 2, 8, 1, 1, 'new-pr.php', NULL, NULL),
(144, 'New Purchase', 2, 8, 1, 1, 'new-purchase.php', NULL, NULL),
(145, 'New Purchase Return', 2, 8, 1, 1, 'new-purchase-returnc.php', NULL, NULL),
(1040, 'Inventory Mapping (Pending)', 3, 0, 1, 9, 'product-bulk-list.php', NULL, NULL),
(147, 'Pending PO Creation', 2, 8, 1, 1, 'manage-pending-tpr2.php', NULL, NULL),
(148, 'Pending Purchase Invoice', 2, 8, 1, 1, 'manage-pending-gpo.php', NULL, NULL),
(149, 'Pending Purchase Return Invoice', 2, 8, 1, 1, 'manage-pending-rgpo.php', NULL, NULL),
(150, 'Pending Inventory', 2, 8, 1, 1, 'NULL', NULL, NULL),
(151, 'Pending Purchase Requisition', 2, 8, 1, 1, 'NULL', NULL, NULL),
(152, 'Pending Purchase Orders', 2, 8, 1, 1, 'manage-pending-po.php', NULL, NULL),
(153, 'Pending Purchase Return', 2, 8, 1, 1, 'manage-pending-po-return.php', NULL, NULL),
(154, 'Purchase Requisition', 2, 8, 1, 1, 'manage-pr.php', NULL, NULL),
(155, 'Assets', 2, 0, 1, 1, 'NULL', NULL, NULL),
(156, 'New Asset ', 3, 155, 1, 1, 'new-asset.php', NULL, NULL),
(157, 'Manage Assets ', 3, 155, 1, 1, 'manage-assets.php', NULL, NULL),
(158, 'Manage Asset Type  ', 3, 155, 1, 1, 'manage-asset-type.php', NULL, NULL),
(159, 'Purchase Orders', 2, 8, 1, 1, 'manage-po.php', NULL, NULL),
(160, 'Purchase Invoices', 2, 8, 1, 1, 'manage-purchase.php', NULL, NULL),
(161, 'Recurring Purchase Invoices ', 2, 8, 1, 1, 'NULL', NULL, NULL),
(162, 'Purchase Return Invoices', 2, 8, 1, 1, 'manage-purchase-return.php', NULL, NULL),
(163, 'Pending Purchase Payments', 2, 8, 1, 1, 'purchase-pending-payments.php', NULL, NULL),
(164, 'Sales Orders', 2, 7, 1, 1, 'manage-so.php', NULL, NULL),
(165, 'Sales Return Invoices', 2, 7, 1, 1, 'manage-sales-return.php', NULL, NULL),
(166, 'Pending Sales Payments', 2, 7, 1, 1, 'sales-pending-payments.php', NULL, NULL),
(167, 'Delivery Option', 2, 7, 1, 1, 'NULL', NULL, NULL),
(168, 'Sales Attachment', 3, 167, 1, 1, 'sd-delivery-pending.php', NULL, NULL),
(169, 'Sales Return Attachment', 3, 167, 1, 1, 'sd-delivery-return-pending.php', NULL, NULL),
(170, 'Payment Recovery', 3, 167, 1, 1, 'sd-delivery-payment-pending.php', NULL, NULL),
(171, 'Route Finalize', 3, 167, 1, 1, 'sd-delivery-route-finalize.php', NULL, NULL),
(172, 'LPO', 2, 7, 1, 1, 'manage-lpo.php', NULL, NULL),
(173, 'New Support Ticket', 3, 33, 0, 2, 'new-support-ticket.php', NULL, NULL),
(174, 'Support Tickets', 3, 33, 0, 2, 'support-list.php', NULL, NULL),
(175, 'Customer Approval', 1, 0, 0, 2, 'customer-pending.php', NULL, NULL),
(176, 'Sales Attachment', 2, 25, 0, 2, 'sd-delivery-pending.php', NULL, NULL),
(177, 'Sales Return Attachment', 2, 25, 0, 2, 'sd-delivery-return-pending.php', NULL, NULL),
(178, 'Sales Orders', 2, 27, 0, 2, 'manage-so.php', NULL, NULL),
(179, 'Sales Return', 2, 27, 0, 2, 'NULL', NULL, NULL),
(180, 'Payment Recovery', 2, 27, 0, 2, 'sd-delivery-payment-pending.php', NULL, NULL),
(669, 'Manage Customer MOQ Profile', 3, 668, 1, 1, 'NULL', NULL, NULL),
(181, 'Payment Recovery', 2, 28, 0, 2, 'sd-delivery-payment-pending.php', NULL, NULL),
(182, 'Route Finalize', 2, 28, 0, 2, 'sd-delivery-route-finalize.php', NULL, NULL),
(183, 'New Sales', 2, 29, 0, 2, 'new-tso-so.php', NULL, NULL),
(184, 'New Return', 2, 29, 0, 2, 'new-tso-return-receipt.php', NULL, NULL),
(185, 'New Receipt Voucher', 2, 29, 0, 2, 'tso-payment-voucher.php', NULL, NULL),
(186, 'Manage Sales Order', 2, 29, 0, 2, 'manage-tso-so.php', NULL, NULL),
(187, 'Manage Sales Return ', 2, 29, 0, 2, 'manage-tso-return.php', NULL, NULL),
(188, 'Manage Receipts', 2, 29, 0, 2, 'tso-payment-receipts.php', NULL, NULL),
(670, 'Customer Stock Summary Report', 3, 0, 1, 1, 'NULL', NULL, NULL),
(189, 'Receive Stock', 2, 30, 0, 2, 'import-products-form.php', NULL, NULL),
(190, 'Return Stock', 2, 30, 0, 2, 'export-products-form.php', NULL, NULL),
(191, 'New Attendance', 2, 19, 1, 9, 'new-tso-attendance.php', NULL, NULL),
(192, 'Manage Attendance', 2, 19, 1, 9, 'manage-tso-attendance.php', NULL, NULL),
(193, 'SO Approval', 2, 14, 1, 1, 'manage-pending-tso.php', NULL, NULL),
(671, 'Stock Inward / Outward Report', 3, 0, 1, 1, 'NULL', NULL, NULL),
(194, 'View SO', 2, 14, 1, 1, 'manage-so.php', NULL, NULL),
(195, 'Sales Return Approval', 2, 14, 1, 1, 'manage-pending-tso-return.php', NULL, NULL),
(196, 'View Sales Return Request', 2, 14, 1, 1, 'manage-so-return.php', NULL, NULL),
(197, 'PR Approval', 2, 14, 0, 13, 'NULL', NULL, NULL),
(198, 'View PR', 2, 14, 0, 13, 'manage-pr.php', NULL, NULL),
(199, 'PO Approval', 2, 14, 1, 1, 'manage-pending-tpo.php', NULL, NULL),
(200, 'View PO', 2, 14, 1, 1, 'manage-po.php', NULL, NULL),
(201, 'Purchase Return Approval', 2, 14, 1, 1, 'manage-pending-tpo-return.php', NULL, NULL),
(202, 'View Purchase Return Request', 2, 14, 1, 1, 'manage-po-return.php', NULL, NULL),
(203, 'New Merchandising Plan', 2, 32, 0, 2, 'NULL', NULL, NULL),
(204, 'Merchandising Plan List', 2, 32, 0, 2, 'NULL', NULL, NULL),
(205, 'New Route', 2, 34, 0, 2, 'new-route.php', NULL, NULL),
(206, 'Routes List', 2, 34, 0, 2, 'route-list.php', NULL, NULL),
(207, 'Booker Day Wise Planner', 2, 34, 0, 2, 'booker-day-wise-planner.php', NULL, NULL),
(208, 'Customer  Routes Mapping', 2, 34, 0, 2, 'customer-route-list.php', NULL, NULL),
(209, 'Pending Customer  Routes Mapping', 2, 34, 0, 2, 'customer-route-list-pending.php', NULL, NULL),
(210, 'BOM', 2, 11, 1, 8, 'item-mapping-list.php', NULL, NULL),
(211, 'Master Production Scheduling', 2, 11, 1, 8, 'NULL', NULL, NULL),
(212, 'Production Job Orders', 2, 11, 1, 8, 'NULL', NULL, NULL),
(213, 'Daily Production', 2, 11, 1, 8, 'NULL', NULL, NULL),
(214, 'Downtime Issues', 2, 11, 1, 8, 'NULL', NULL, NULL),
(215, 'Machine / Workstation', 2, 11, 1, 8, 'NULL', NULL, NULL),
(216, 'Production Shift', 2, 11, 1, 8, 'NULL', NULL, NULL),
(217, 'Production Department', 2, 11, 1, 8, 'NULL', NULL, NULL),
(218, 'New MPS', 3, 211, 1, 8, 'new-production-planning.php', NULL, NULL),
(219, 'Manage MPS', 3, 211, 1, 8, 'mps-list.php', NULL, NULL),
(220, 'New Job Order', 3, 212, 1, 8, 'new-job-order.php', NULL, NULL),
(221, 'Job Order List', 3, 212, 1, 8, 'rmr-list.php', NULL, NULL),
(222, 'Daily Production Entry', 3, 213, 1, 8, 'workstation-entry.php', NULL, NULL),
(223, 'Daily Production List', 3, 213, 1, 8, 'production-list.php', NULL, NULL),
(224, 'Simple Production Entry', 3, 213, 1, 8, 'final-production.php', NULL, NULL),
(225, 'New Downtime Entry', 3, 214, 1, 8, 'downtime-entry.php', NULL, NULL),
(226, 'Manage Downtime Entry', 3, 214, 1, 8, 'manage-downtime-entry.php', NULL, NULL),
(227, 'New Machine', 3, 215, 1, 8, 'new-machine.php', NULL, NULL),
(228, 'Manage Machine', 3, 215, 1, 8, 'machine-list.php', NULL, NULL),
(229, 'New machine type', 3, 215, 1, 8, 'new-machine-type.php', NULL, NULL),
(230, 'Manage machine type', 3, 215, 1, 8, 'machine-type-list.php', NULL, NULL),
(231, 'New Shift', 3, 216, 1, 8, 'new-production-shift.php', NULL, NULL),
(232, 'Manage Shift', 3, 216, 1, 8, 'manage-production-shift.php', NULL, NULL),
(233, 'New Production Department', 3, 217, 1, 8, 'new-production-department.php', NULL, NULL),
(234, 'Manage Production Department', 3, 217, 1, 8, 'production-department-list.php', NULL, NULL),
(235, 'New Demo Plot', 2, 41, 0, 3, 'new-demo-plot.php', NULL, NULL),
(236, 'Demo Plot List', 2, 41, 0, 3, 'manage-demo-plot.php', NULL, NULL),
(237, 'New Quiz', 2, 43, 0, 3, 'new-quiz.php', NULL, NULL),
(238, 'Quiz List', 2, 43, 0, 3, 'quiz-list.php', NULL, NULL),
(239, 'Quiz Response List', 2, 43, 0, 3, 'quiz-response-list.php', NULL, NULL),
(240, 'New Expense', 2, 40, 0, 3, 'new-marketing-expense.php', NULL, NULL),
(241, 'Expense List', 2, 40, 0, 3, 'manage-marketing-expense.php', NULL, NULL),
(242, 'Expense Type', 2, 40, 0, 3, 'NULL', NULL, NULL),
(243, 'Travelling Chart', 2, 40, 0, 3, 'NULL', NULL, NULL),
(244, 'New Expense Type', 3, 242, 0, 3, 'new-mexpense-type.php', NULL, NULL),
(245, 'Manage Expense Type', 3, 242, 0, 3, 'mexpense-type-list.php', NULL, NULL),
(247, 'Surveyor List', 2, 37, 0, 3, 'salesforce-list.php', NULL, NULL),
(248, 'Surveyor Bulk Settings', 2, 37, 0, 3, 'salesman-bulk-settings.php', NULL, NULL),
(249, 'Team', 2, 37, 0, 3, 'NULL', NULL, NULL),
(250, 'New Team', 3, 249, 0, 3, 'new-distributor.php', NULL, NULL),
(251, 'Distributor List', 3, 249, 0, 2, 'distributor-list.php', NULL, NULL),
(252, 'New Booker / Salesman ', 2, 24, 1, 2, 'new-salesman.php', NULL, NULL),
(253, 'Manage Booker / Salesman', 2, 24, 1, 2, 'salesforce-list.php', NULL, NULL),
(254, 'Booker / Salesman Bulk Settings', 2, 24, 0, 2, 'salesman-bulk-settings.php', NULL, NULL),
(255, 'Booker / Saleman Target', 2, 24, 0, 2, 'salesman-target.php', NULL, NULL),
(256, 'New Block', 2, 35, 0, 2, 'new-salesman-block.php', NULL, NULL),
(257, 'Block List', 2, 35, 0, 2, 'salesforce-block-list.php', NULL, NULL),
(258, 'Block Levels', 2, 35, 0, 2, 'NULL', NULL, NULL),
(259, 'Routes Block Mapping', 2, 35, 0, 2, 'route-block-list.php', NULL, NULL),
(260, 'Pending Routes Block Mapping', 2, 35, 0, 2, 'route-block-list-pending.php', NULL, NULL),
(261, 'New Block Level', 3, 258, 0, 2, 'new-block-level.php', NULL, NULL),
(262, 'Manage Block Level', 3, 258, 0, 2, 'block-level-list.php', NULL, NULL),
(263, 'New Activity', 2, 42, 0, 3, 'new-marketing-activity.php', NULL, NULL),
(264, 'Activity List', 2, 42, 0, 3, 'manage-marketing-activity.php', NULL, NULL),
(265, 'Activity Type', 2, 42, 0, 3, 'NULL', NULL, NULL),
(266, 'New Activity Type', 3, 265, 0, 3, 'new-mactivity-type.php', NULL, NULL),
(267, 'Manage Activity Type', 3, 265, 0, 3, 'mactivity-type-list.php', NULL, NULL),
(268, 'Leads', 2, 12, 1, 7, 'NULL', NULL, NULL),
(269, 'Follow Up', 2, 12, 1, 7, 'NULL', NULL, NULL),
(270, 'Quotation', 2, 12, 1, 7, 'NULL', NULL, NULL),
(271, 'New Lead', 3, 268, 1, 7, 'new-lead.php', NULL, NULL),
(272, 'Manage Leads', 3, 268, 1, 7, 'manage-lead.php', NULL, NULL),
(5273, 'Lead Transfer', 3, 268, 1, 7, 'lead-transfer.php', NULL, NULL),
(4116, 'New Client Department', 3, 271, 1, 7, 'lead/new-client-department.php', NULL, NULL),
(273, 'New Follow Up', 3, 269, 1, 7, 'new-followup.php', NULL, NULL),
(274, 'Manage Follow Up', 3, 269, 1, 7, 'manage-followup.php', NULL, NULL),
(275, 'New Quotation', 3, 270, 1, 7, 'new-quotation.php', NULL, NULL),
(276, 'Manage Quotation', 3, 270, 1, 7, 'manage-quotation.php', NULL, NULL),
(277, 'New Expense', 2, 9, 1, 1, 'new-marketing-expense.php', NULL, NULL),
(278, 'Manage Expense', 2, 9, 1, 1, 'NULL', NULL, NULL),
(279, 'Expense Payable', 2, 9, 1, 1, 'NULL', NULL, NULL),
(280, 'Manage Recurring Expense', 2, 9, 1, 1, 'NULL', NULL, NULL),
(281, 'Manage Expense Type', 2, 9, 1, 1, 'mexpense-type-list.php', NULL, NULL),
(282, 'Expense Vendor', 2, 9, 1, 1, 'NULL', NULL, NULL),
(283, 'New Vendor', 3, 282, 1, 1, 'new-vendor.php', NULL, NULL),
(284, 'Manage Vendor', 3, 282, 1, 1, 'vendor-list.php', NULL, NULL),
(672, 'Stock Inward / Outward Summary Report', 3, 0, 1, 1, 'warehouse-unit-activity-summary.php', NULL, NULL),
(286, 'Internal product transfer', 2, 6, 1, 1, 'NULL', NULL, NULL),
(287, 'External product transfer', 2, 6, 1, 1, 'NULL', NULL, NULL),
(288, 'Internal material transfer', 2, 6, 1, 1, 'NULL', NULL, NULL),
(289, 'Goods Delivery Note (Sale)', 2, 6, 1, 1, 'NULL', NULL, NULL),
(290, 'Goods Receiving Note (Sale Return)', 2, 6, 1, 1, 'NULL', NULL, NULL),
(291, 'Goods Receiving Note (Purchase)', 2, 6, 1, 1, 'NULL', NULL, NULL),
(292, 'Goods Delivery Note (Purchase Return)', 2, 6, 1, 1, 'NULL', NULL, NULL),
(608, 'Booker Sales Report (Unexecuted)', 3, 17, 0, 2, 'master-sales-report.php', NULL, NULL),
(293, 'Floor Material Movement', 2, 6, 1, 8, 'NULL', NULL, NULL),
(294, 'Transfer Stock', 3, 286, 1, 1, 'transfer-stock.php', NULL, NULL),
(295, 'Transfer List', 3, 286, 1, 1, 'warehouse-transfer-list.php', NULL, NULL),
(296, 'Stock in Transit', 3, 286, 1, 1, 'warehouse-transfer-confirmation-list.php', NULL, NULL),
(6046, 'Smart Transfer Suggestions', 3, 286, 1, 1, 'smart-transfer.php', NULL, NULL),
(297, 'Stock In Form', 3, 287, 1, 1, 'stock-in.php', NULL, NULL),
(298, 'Manage Stock In', 3, 287, 1, 1, 'manage-stock-in.php', NULL, NULL),
(299, 'Stock Out Form', 3, 287, 1, 1, 'stock-out.php', NULL, NULL),
(300, 'Manage Stock Out', 3, 287, 1, 1, 'manage-stock-out.php', NULL, NULL),
(301, 'Transfer Stock', 3, 288, 1, 1, 'transfer-stock.php', NULL, NULL),
(302, 'Transfer List', 3, 288, 1, 1, 'warehouse-transfer-list.php', NULL, NULL),
(303, 'Stock in Transit', 3, 288, 1, 1, 'warehouse-transfer-confirmation-list.php', NULL, NULL),
(304, 'Pending GDN', 3, 289, 1, 1, 'manage-pending-gdn.php', NULL, NULL),
(305, 'Manage GDN', 3, 289, 1, 1, 'manage-gdn.php', NULL, NULL),
(306, 'Pending GRN', 3, 290, 1, 1, 'manage-pending-rgrn.php', NULL, NULL),
(307, 'Manage GRN', 3, 290, 1, 1, 'manage-rgrn.php', NULL, NULL),
(308, 'Pending GRN', 3, 291, 1, 1, 'manage-pending-grn.php', NULL, NULL),
(309, 'Manage GRN', 3, 291, 1, 1, 'manage-grn.php', NULL, NULL),
(310, 'Pending GDN', 3, 292, 1, 1, 'manage-pending-rgdn.php', NULL, NULL),
(311, 'Manage GDN', 3, 292, 1, 1, 'manage-rgdn.php', NULL, NULL),
(312, 'Material requisition form', 3, 293, 1, 8, 'stock-request-form.php', NULL, NULL),
(313, 'Pending Material requisition Issuance list', 3, 293, 1, 8, 'manage-pending-mrf.php', NULL, NULL),
(314, 'Material requisition list', 3, 293, 1, 8, 'manage-mrf.php', NULL, NULL),
(315, 'Material Return Request', 3, 293, 1, 8, 'stock-return-form.php', NULL, NULL),
(317, 'Material Return list', 3, 293, 1, 8, 'manage-mrrf.php', NULL, NULL),
(318, 'BA Management', 2, 21, 0, 4, 'NULL', NULL, NULL),
(319, 'Tertiary Sale', 2, 21, 0, 4, 'NULL', NULL, NULL),
(320, 'Tertiary Return', 2, 21, 0, 4, 'NULL', NULL, NULL),
(321, 'Merchandising', 2, 21, 0, 4, 'NULL', NULL, NULL),
(322, 'Customer Survey', 2, 21, 0, 4, 'NULL', NULL, NULL),
(323, 'Import Targets', 2, 21, 0, 4, 'import-bul-target.php', NULL, NULL),
(324, 'New Tertiary Sale', 3, 319, 0, 4, 'new-tertiary.php', NULL, NULL),
(325, 'Manage Tertiary Sale', 3, 319, 0, 4, 'manage-tertiary.php', NULL, NULL),
(326, 'New Tertiary Return', 3, 320, 0, 4, 'new-tertiary-return.php', NULL, NULL),
(327, 'Manage Tertiary Return', 3, 320, 0, 4, 'manage-tertiary-return.php', NULL, NULL),
(328, 'New Merchandising', 3, 321, 0, 4, 'new-merchandising.php', NULL, NULL),
(329, 'Manage Merchandising', 3, 321, 0, 4, 'manage-merchandising.php', NULL, NULL),
(330, 'New Customer Survey', 3, 322, 0, 4, 'new-customer-survey.php', NULL, NULL),
(331, 'Manage Customer Survey', 3, 322, 0, 4, 'manage-customer-survey.php', NULL, NULL),
(332, 'New Distributor', 2, 31, 0, 2, 'new-distributor.php', NULL, NULL),
(334, 'Distributor Status', 2, 31, 0, 2, 'distributor-activity.php', NULL, NULL),
(335, 'Stock Management', 2, 31, 0, 2, 'NULL', NULL, NULL),
(336, 'Internal product transfer', 2, 31, 0, 2, 'NULL', NULL, NULL),
(337, 'Adjustments', 2, 31, 0, 2, 'NULL', NULL, NULL),
(338, 'Import Stock (CSV)', 3, 335, 0, 2, 'import-products.php', NULL, NULL),
(339, 'Import Stock (Form)', 3, 335, 0, 2, 'NULL', NULL, NULL),
(340, 'Import Stock (API)', 3, 335, 0, 2, 'NULL', NULL, NULL),
(341, 'Transfer Stock', 3, 336, 0, 2, 'transfer-stock.php', NULL, NULL),
(342, 'Transfer List', 3, 336, 0, 2, 'warehouse-transfer-list.php', NULL, NULL),
(343, 'New Quantity Adjustment', 3, 337, 0, 2, 'new-quantity-adjustment.php', NULL, NULL),
(344, 'Quantity Adjustment History', 3, 337, 0, 2, 'quantity-adjustment-history.php', NULL, NULL),
(345, 'New Vendor', 2, 5, 1, 1, 'new-vendor.php', NULL, NULL),
(346, 'Vendor List', 2, 5, 1, 1, 'vendor-list.php', NULL, NULL),
(347, 'Debit Note', 2, 5, 1, 1, 'NULL', NULL, NULL),
(348, 'Credit Note', 2, 5, 1, 1, 'NULL', NULL, NULL),
(349, 'Vendor Type', 2, 5, 1, 1, 'NULL', NULL, NULL),
(350, 'Vendor Brand Discount', 2, 5, 1, 1, 'vb-discount.php', NULL, NULL),
(351, 'New Debit Note', 2, 347, 1, 1, 'purchase-debit-note.php', NULL, NULL),
(352, 'Manage Debit Note', 2, 347, 1, 1, 'vdebit-note-list.php', NULL, NULL),
(353, 'New Credit Note', 2, 348, 1, 1, 'purchase-credit-note.php', NULL, NULL),
(354, 'Manage Credit Note', 3, 348, 1, 1, 'vcredit-note-list.php', NULL, NULL),
(355, 'New Vendor Type', 3, 349, 1, 1, 'new-vendor-type.php', NULL, NULL),
(356, 'Manage Vendor Type', 3, 349, 1, 1, 'manage-vendor-type.php', NULL, NULL),
(357, 'Vendor Type Pricing', 3, 349, 1, 1, 'vb-price.php', NULL, NULL),
(358, 'Vendor Type Discount', 3, 349, 1, 1, 'vb-discount1.php', NULL, NULL),
(359, 'Vedor Type Discount 2', 3, 349, 1, 1, 'NULL', NULL, NULL),
(360, 'Vendor Type Discount 3', 3, 349, 1, 1, 'NULL', NULL, NULL),
(361, 'Vendor Type Trade Offer', 3, 349, 1, 1, 'NULL', NULL, NULL),
(362, 'Vendor Type Scheme', 3, 349, 1, 1, 'NULL', NULL, NULL),
(363, 'Vendor Type Tax 1', 3, 349, 1, 1, 'vb-tax1.php', NULL, NULL),
(364, 'Vendor Type Tax 2', 3, 349, 1, 1, 'NULL', NULL, NULL),
(365, 'Vendor Type Tax 3', 3, 349, 1, 1, 'NULL', NULL, NULL),
(366, 'New Customer', 2, 4, 1, 1, 'new-customer.php', NULL, NULL),
(367, 'Customer List', 2, 4, 1, 1, 'customer-list.php', NULL, NULL),
(369, 'Pricing Type', 2, 4, 1, 1, 'NULL', NULL, NULL),
(370, 'Customer Slabs', 2, 4, 1, 1, 'NULL', NULL, NULL),
(371, 'Customer Category', 2, 4, 1, 1, 'NULL', NULL, NULL),
(372, 'Customer sub category', 2, 4, 1, 1, 'NULL', NULL, NULL),
(373, 'Invoice based discount', 2, 4, 1, 1, 'cbi-discount.php', NULL, NULL),
(6047, 'Item based discount (Rs)', 2, 4, 1, 1, 'cbi-discountrs.php', NULL, NULL),
(374, 'Customer brand discount', 2, 4, 1, 1, 'cb-discount.php', NULL, NULL),
(375, 'Customer list (Inactive)', 2, 4, 1, 1, 'customer-list-inactive.php', NULL, NULL),
(376, '{$subCustomerPluralLabel}', 2, 4, 1, 1, 'NULL', NULL, NULL),
(377, 'Credit Note', 2, 4, 1, 1, 'NULL', NULL, NULL),
(378, 'Debit Note', 2, 4, 1, 1, 'NULL', NULL, NULL),
(379, 'New Credit Note', 3, 377, 1, 1, 'sales-credit-note.php', NULL, NULL),
(380, 'Manage Credit Note', 3, 377, 1, 1, 'scredit-note-list.php', NULL, NULL),
(381, 'New Debit Note', 3, 378, 1, 1, 'sales-debit-note.php', NULL, NULL),
(382, 'Manage Debit Note', 3, 378, 1, 1, 'sdebit-note-list.php', NULL, NULL),
(383, 'New {$subCustomerLabel}', 3, 376, 1, 1, 'new-sub-customer.php', NULL, NULL),
(384, 'Manage {$subCustomerLabel}', 3, 376, 1, 1, 'sub-customer-list.php', NULL, NULL),
(673, 'Export Advice', 2, 10, 0, 6, 'NULL', NULL, NULL),
(385, 'New Pricing Type', 3, 369, 1, 1, 'new-customer-type.php', NULL, NULL),
(386, 'Manage Pricing Type', 3, 369, 1, 1, 'manage-customer-type.php', NULL, NULL),
(387, 'New Bulk Pricing', 3, 369, 1, 1, 'cb-bulk-price.php', NULL, NULL),
(388, 'Manage Bulk Pricing', 3, 369, 1, 1, 'multi-pricing-list.php', NULL, NULL),
(389, 'Pricing Sheet', 3, 369, 1, 1, 'cb-price.php', NULL, NULL),
(390, 'Import Pricing Sheet', 3, 369, 1, 1, 'import-customer-pricing.php', NULL, NULL),
(391, 'Pricing Type Disc', 3, 369, 1, 1, 'cb-discount1.php', NULL, NULL),
(392, 'Pricing Type Disc 2', 3, 369, 1, 1, 'NULL', NULL, NULL),
(393, 'Pricing Type Disc 3', 3, 369, 1, 1, 'NULL', NULL, NULL),
(394, 'Pricing Type T.Offer', 3, 369, 1, 1, 'NULL', NULL, NULL),
(395, 'Pricing Type Scheme', 3, 369, 1, 1, 'cb-scheme.php', NULL, NULL),
(396, 'Pricing Type Tax 1', 3, 369, 1, 1, 'cb-tax1.php', NULL, NULL),
(397, 'Pricing Type Tax 2', 3, 369, 1, 1, 'NULL', NULL, NULL),
(398, 'Pricing Type Tax 3', 3, 369, 1, 1, 'NULL', NULL, NULL),
(399, 'New Doctor', 2, 14, 0, 3, 'new-doctor.php', NULL, NULL),
(400, 'Manage Doctor', 2, 14, 0, 3, 'doctor-list.php', NULL, NULL),
(401, 'Doctor Class', 2, 14, 0, 3, 'NULL', NULL, NULL),
(402, 'Doctor Speciality', 2, 14, 0, 3, 'NULL', NULL, NULL),
(403, 'Doctor Qualification', 2, 14, 0, 3, 'NULL', NULL, NULL),
(404, 'Clinic Type', 2, 14, 0, 3, 'NULL', NULL, NULL),
(405, 'Manage Doctor Duplication', 2, 14, 0, 3, 'NULL', NULL, NULL),
(406, 'Manage Doctor Pools', 2, 14, 0, 3, 'NULL', NULL, NULL),
(407, 'Import Doctors', 2, 14, 0, 3, 'import-doctors.php', NULL, NULL),
(674, 'New Export', 3, 673, 0, 6, 'NULL', NULL, NULL),
(408, 'New Doctor Class', 3, 401, 0, 3, 'new-doctor-type.php', NULL, NULL),
(409, 'Manage Doctor Class', 3, 401, 0, 3, 'doctor-type-list.php', NULL, NULL),
(410, 'New Doctor Speciality', 3, 402, 0, 3, 'new-doctor-speciality.php', NULL, NULL),
(411, 'Manage Doctor Speciality', 3, 402, 0, 3, 'doctor-speciality-list.php', NULL, NULL),
(412, 'New Doctor Qualification', 3, 403, 0, 3, 'new-doctor-qualification.php', NULL, NULL),
(413, 'Manage Doctor Qualification', 3, 403, 0, 3, 'doctor-qualification-list.php', NULL, NULL),
(414, 'New Clinic Type', 3, 404, 0, 3, 'new-clinic-type.php', NULL, NULL),
(415, 'Manage Clinic Type', 3, 404, 0, 3, 'clinic-type-list.php', NULL, NULL),
(416, 'New Pharmacy', 2, 39, 0, 3, 'new-pharmacy.php', NULL, NULL),
(417, 'Manage Pharmacy', 2, 39, 0, 3, 'pharmacy-list.php', NULL, NULL),
(418, 'Pharmacy Type', 2, 39, 0, 3, 'NULL', NULL, NULL),
(419, 'Manage Pharmacy Duplication', 2, 39, 0, 3, 'NULL', NULL, NULL),
(420, 'Manage Pharmacies Pools', 2, 39, 0, 3, 'NULL', NULL, NULL),
(421, 'Import Pharmacies', 2, 39, 0, 3, 'NULL', NULL, NULL),
(422, 'New Pharmacy Type', 3, 418, 0, 3, 'new-pharmacy-type.php', NULL, NULL),
(423, 'Manage Pharmacy Type', 3, 418, 0, 3, 'pharmacy-type-list.php', NULL, NULL),
(424, 'New Product', 2, 2, 1, 1, 'new-item.php', NULL, NULL),
(425, 'Product List', 2, 2, 1, 1, 'item-list.php', NULL, NULL),
(426, 'Batch management', 2, 2, 1, 10, 'NULL', NULL, NULL),
(427, 'Product Type', 2, 2, 1, 1, 'NULL', NULL, NULL),
(428, 'Product sub type', 2, 2, 1, 1, 'NULL', NULL, NULL),
(429, 'Product brand', 2, 2, 1, 1, 'NULL', NULL, NULL),
(430, 'Product Franchise', 2, 2, 1, 1, 'NULL', NULL, NULL),
(431, 'Product Type', 2, 2, 1, 1, 'NULL', NULL, NULL),
(432, 'Product status', 2, 2, 1, 1, 'NULL', NULL, NULL),
(433, 'Product Unit', 2, 2, 1, 1, 'NULL', NULL, NULL),
(434, 'Adjustments', 2, 2, 1, 1, 'NULL', NULL, NULL),
(435, 'Update Product Pricing', 2, 2, 1, 1, 'import-products2.php', NULL, NULL),
(436, 'Bulk Product creation', 2, 2, 1, 1, 'NULL', NULL, NULL),
(437, 'New Batch', 3, 426, 1, 10, 'NULL', NULL, NULL),
(438, 'Manage Batch', 3, 426, 1, 10, 'NULL', NULL, NULL),
(439, 'Manage Batch (IMEI)', 3, 426, 1, 10, 'NULL', NULL, NULL),
(440, 'New Product Type', 3, 427, 1, 1, 'new-item-type.php', NULL, NULL),
(441, 'Manage product type', 3, 427, 1, 1, 'manage-item-type.php', NULL, NULL),
(442, 'New product sub type', 3, 428, 1, 1, 'new-item-subtype.php', NULL, NULL),
(443, 'Manage product sub type', 3, 428, 1, 1, 'manage-item-subtype.php', NULL, NULL),
(444, 'New product brand', 3, 429, 1, 1, 'new-brand.php', NULL, NULL),
(445, 'Manage product brand', 3, 429, 1, 1, 'brand-list.php', NULL, NULL),
(446, 'New product franchise', 3, 430, 1, 1, 'new-product-franchise.php', NULL, NULL),
(447, 'Manage product franchise', 3, 430, 1, 1, 'manage-product-franchise.php', NULL, NULL),
(448, 'New product type', 3, 431, 1, 1, 'new-item-type.php', NULL, NULL),
(449, 'Manage product type', 3, 431, 1, 1, 'manage-item-type.php', NULL, NULL),
(450, 'New product status', 3, 432, 1, 1, 'new-product-status.php', NULL, NULL),
(451, 'Manage product status', 3, 432, 1, 1, 'manage-product-status.php', NULL, NULL),
(452, 'New product unit', 3, 433, 1, 1, 'new-product-unit.php', NULL, NULL),
(453, 'Manage product unit', 3, 433, 1, 1, 'manage-product-unit.php', NULL, NULL),
(454, 'Add product stock', 3, 434, 1, 1, 'add-product-opening.php', NULL, NULL),
(455, 'Manage product stock', 3, 434, 1, 1, 'manage-product-opening.php', NULL, NULL),
(456, 'New quantity adjustment', 3, 434, 1, 1, 'new-quantity-adjustment.php', NULL, NULL),
(457, 'Quantity adjustment history', 3, 434, 1, 1, 'quantity-adjustment-history.php', NULL, NULL),
(458, 'New cost adjustment', 3, 434, 1, 1, 'new-cost-adjustment.php', NULL, NULL),
(459, 'Cost adjustment history', 3, 434, 1, 1, 'cost-adjustment-history.php', NULL, NULL),
(483, 'Employee Dashboard', 2, 18, 1, 9, 'employee-center.php', NULL, NULL),
(461, 'New Raw Material', 2, 3, 1, 12, 'new-component.php', NULL, NULL),
(462, 'Manage Raw material', 2, 3, 1, 12, 'component-list.php', NULL, NULL),
(463, 'Batch Management', 2, 3, 0, 10, 'NULL', NULL, NULL),
(464, 'Raw material quality', 2, 3, 1, 12, 'NULL', NULL, NULL),
(465, 'Raw material type', 2, 3, 1, 12, 'NULL', NULL, NULL),
(466, 'Raw material unit', 2, 3, 1, 12, 'NULL', NULL, NULL),
(467, 'Adjustment', 2, 3, 1, 12, 'NULL', NULL, NULL),
(468, 'Import raw material', 2, 3, 1, 12, 'import-material.php', NULL, NULL),
(469, 'New Batch', 3, 463, 0, 10, 'NULL', NULL, NULL),
(470, 'Manage Batch', 3, 463, 0, 10, 'NULL', NULL, NULL),
(471, 'Manage Batch (Inactive)', 3, 463, 0, 10, 'NULL', NULL, NULL),
(472, 'New Raw material quality', 3, 464, 1, 12, 'new-component-quality.php', NULL, NULL),
(473, 'Manage raw material quality', 3, 464, 1, 12, 'manage-component-quality.php', NULL, NULL),
(474, 'New Raw material type', 3, 465, 1, 12, 'new-component-type.php', NULL, NULL),
(475, 'Manage Raw material type', 3, 465, 1, 12, 'manage-component-type.php', NULL, NULL),
(476, 'New Raw material unit', 3, 466, 1, 12, 'new-component-unit.php', NULL, NULL),
(477, 'Manage Raw material unit', 3, 466, 1, 12, 'manage-component-unit.php', NULL, NULL),
(478, 'Manage Raw material stock', 3, 467, 1, 12, 'manage-product-opening2.php', NULL, NULL),
(479, 'New quantity adjustment', 3, 467, 1, 12, 'new-quantity-adjustment.php', NULL, NULL),
(480, 'Quantity adjustment history', 3, 467, 1, 12, 'quantity-adjustment-history.php', NULL, NULL),
(481, 'New Cost adjustment', 3, 467, 0, 12, 'new-cost-adjustment.php', NULL, NULL),
(482, 'Cost adjustment history', 3, 467, 0, 12, 'cost-adjustment-history.php', NULL, NULL),
(675, 'Manage Export', 3, 673, 0, 6, 'NULL', NULL, NULL),
(484, 'Employee Management', 2, 18, 1, 9, 'NULL', NULL, NULL),
(485, 'Employee Bulk Management', 2, 18, 1, 9, 'employee-bulk-list.php', NULL, NULL),
(486, 'Employee Location Management', 2, 18, 1, 9, 'employee-location-list.php', NULL, NULL),
(6201, 'New Marketing Data', 3, 268, 1, 7, 'lead/new-marketing-data.php', NULL, NULL),
(6202, 'Manage Marketing Data', 3, 268, 1, 7, 'lead/manage-marketing-data.php', NULL, NULL),

(6000, 'Recruitment Dashboard', 2, 18, 1, 9, 'recruitment-dashboard.php', NULL, NULL),
(6001, 'Recruitment Candidates', 2, 18, 1, 9, 'recruitment-candidates.php', NULL, NULL),
(6002, 'Add Candidate', 2, 18, 1, 9, 'recruitment-new-candidate.php', NULL, NULL),
(6003, 'Candidate Profile', 2, 18, 1, 9, 'recruitment-view.php', NULL, NULL),
(6004, 'Recruitment Menu', 2, 18, 1, 9, 'NULL', NULL, NULL),
(487, 'Payroll Center', 2, 18, 1, 9, 'NULL', NULL, NULL),
(488, 'Attendance Management', 2, 18, 1, 9, 'NULL', NULL, NULL),
(489, 'Leave Management', 2, 18, 1, 9, 'NULL', NULL, NULL),
(490, 'Shift Management', 2, 18, 1, 9, 'NULL', NULL, NULL),
(491, 'Allowances &amp; Benefits', 2, 18, 1, 9, 'NULL', NULL, NULL),
(492, 'Performance Assessment &amp; Appraisals', 2, 18, 1, 9, 'NULL', NULL, NULL),
(493, 'Fines &amp; Deduction', 2, 18, 1, 9, 'NULL', NULL, NULL),
(494, 'Loans Management', 2, 18, 1, 9, 'NULL', NULL, NULL),
(495, 'Expense Claims', 2, 18, 1, 9, 'NULL', NULL, NULL),
(496, 'Insurance Claims', 2, 18, 1, 9, 'NULL', NULL, NULL),
(497, 'Event Planner', 2, 18, 1, 9, 'NULL', NULL, NULL),
(498, 'General Notification', 2, 18, 1, 9, 'NULL', NULL, NULL),
(499, 'New Notification', 3, 498, 1, 9, 'new-notification.php', NULL, NULL),
(500, 'Manage Notifications', 3, 498, 1, 9, 'manage-notification.php', NULL, NULL),
(501, 'New Event', 3, 497, 1, 9, 'new-event.php', NULL, NULL),
(502, 'Manage Event', 3, 497, 1, 9, 'event-list.php', NULL, NULL),
(503, 'Event Calendar', 3, 497, 1, 9, 'event-calendar.php', NULL, NULL),
(504, 'Claim Request', 3, 496, 1, 9, 'new-expense-request.php', NULL, NULL),
(505, 'Claim Status', 3, 496, 1, 9, 'expense-request-status.php', NULL, NULL),
(506, 'Manage Pending Claims', 3, 496, 1, 9, 'manage-pending-eclaims.php', NULL, NULL),
(507, 'Manage Issued Claims', 3, 496, 1, 9, 'manage-employee-eclaims.php', NULL, NULL),
(676, 'Import Employee', 2, 18, 1, 9, 'import-employee.php', NULL, NULL),
(508, 'Expense Request', 3, 495, 1, 9, 'new-expense-request.php', NULL, NULL),
(509, 'Claim Status', 3, 495, 1, 9, 'expense-request-status.php', NULL, NULL),
(510, 'Manage Pending Expense Claims', 3, 495, 1, 9, 'manage-pending-eclaims.php', NULL, NULL),
(511, 'Manage Issued Expense Claims', 3, 495, 1, 9, 'manage-employee-eclaims.php', NULL, NULL),
(512, 'Loan Request', 3, 494, 1, 9, 'new-loan-request.php', NULL, NULL),
(513, 'Loans & Advances Line Approval', 3, 494, 1, 9, 'loan-request-status.php', NULL, NULL),
(514, 'Manage Pending Loans', 3, 494, 1, 9, 'manage-pending-loans.php', NULL, NULL),
(515, 'Manage Issued Loans', 3, 494, 1, 9, 'manage-employee-loans.php', NULL, NULL),
(516, 'New Fine', 3, 493, 1, 9, 'new-employee-fine.php', NULL, NULL),
(517, 'Manage Fines', 3, 493, 1, 9, 'manage-employee-fines.php', NULL, NULL),
(518, 'Manage Pending Fines', 3, 493, 1, 9, 'manage-employee-fines-pending.php', NULL, NULL),
(519, 'New Fine Type', 3, 493, 1, 9, 'new-fine-type.php', NULL, NULL),
(520, 'Manage Fine Type ', 3, 493, 1, 9, 'manage-employee-fines.php', NULL, NULL),
(521, 'New Performance Assessment Request', 3, 492, 1, 9, 'new-appraisal-request.php', NULL, NULL),
(522, 'Performance Assessment Request Line Manager Status ', 3, 492, 1, 9, 'appraisal-request-status.php', NULL, NULL),
(523, ' Manage Pending Performance Appraisal', 3, 492, 1, 9, 'manage-pending-appraisals.php', NULL, NULL),
(524, 'New Assesment Criteria', 3, 492, 1, 9, 'new-assessment-criteria.php', NULL, NULL),
(525, 'Manage Assesment Criteria', 3, 492, 1, 9, 'manage-assessment-criteria.php', NULL, NULL),
(526, 'New Allowances Type', 3, 491, 1, 9, 'new-allowance.php', NULL, NULL),
(527, 'Manage Allowance Type', 3, 491, 1, 9, 'manage-allowances.php', NULL, NULL),
(528, 'New Shift', 3, 490, 1, 9, 'new-employee-shift.php', NULL, NULL),
(529, 'Manage Shift', 3, 490, 1, 9, 'manage-employee-shift.php', NULL, NULL),
(530, 'Employee Shift Switcher', 3, 490, 1, 9, 'employee-shift-management.php', NULL, NULL),
(531, 'Request Leave', 3, 489, 1, 9, 'new-leave-request.php', NULL, NULL),
(532, 'Leaves Line Approval', 3, 489, 1, 9, 'leave-request-status.php', NULL, NULL),
(533, 'Manage Leaves', 3, 489, 1, 9, 'leave-request-list.php', NULL, NULL),
(534, 'New Leaves Type', 3, 489, 1, 9, 'new-leave-type.php', NULL, NULL),
(535, 'Manage Leaves Type', 3, 489, 1, 9, 'leave-type-list.php', NULL, NULL),
(536, 'Leaves Calendar', 3, 489, 1, 9, 'leaves-calendar.php', NULL, NULL),
(537, 'Import Attendance', 3, 488, 1, 9, 'import-employee-attendance.php', NULL, NULL),
(538, 'Add Attendance', 3, 488, 1, 9, 'new-employee-attendance.php', NULL, NULL),
(539, 'Manage Attendance', 3, 488, 1, 9, 'manage-employee-attendance.php', NULL, NULL),
(540, 'Clock In / Clock Out', 3, 488, 1, 9, 'clock-in.php', NULL, NULL),
(541, 'Generate Payroll Slips', 3, 487, 1, 9, 'issue-salary.php', NULL, NULL),
(542, 'Print Payroll Slips', 3, 487, 1, 9, 'print-payroll-details.php', NULL, NULL),
(543, 'Payroll List', 3, 487, 1, 9, 'payroll-list.php', NULL, NULL),
(544, 'Salary List', 3, 487, 1, 9, 'salary-list.php', NULL, NULL),
(545, 'Add Salary Policy', 3, 487, 1, 9, 'new-salary-slab.php', NULL, NULL),
(546, 'Manage Salary Policy', 3, 487, 1, 9, 'salary-slab-list.php', NULL, NULL),
(547, 'New Employee', 3, 484, 1, 9, 'new-employee.php', NULL, NULL),
(548, 'Employee List', 3, 484, 1, 9, 'employee-list.php', NULL, NULL),
(6481, 'Employee Stage Payroll', 3, 484, 1, 9, 'employee-stage-payroll.php', NULL, NULL),
(6482, 'Employee Stage Admin', 3, 484, 1, 9, 'employee-stage-admin.php', NULL, NULL),
(6483, 'Employee Stage HR Approval', 3, 484, 1, 9, 'employee-stage-payroll-final.php', NULL, NULL),
(6484, 'Employee Stage Department Approval', 3, 484, 1, 9, 'employee-stage-gm.php', NULL, NULL),
(6485, 'Employee Stage Final Approval', 3, 484, 1, 9, 'employee-stage-final.php', NULL, NULL),
(549, 'Employee List (Inactive)', 3, 484, 1, 9, 'employee-list-inactive.php', NULL, NULL),
(550, 'Document Management', 3, 484, 1, 9, 'staff-documents.php', NULL, NULL),
(551, 'Employee Directory', 3, 484, 1, 9, 'staff-directory.php', NULL, NULL),
(552, 'User Accounts', 2, 13, 1, 1, 'NULL', NULL, NULL),
(553, 'Backup / Restore', 2, 13, 1, 1, 'NULL', NULL, NULL),
(554, 'Transporter', 2, 13, 1, 1, 'NULL', NULL, NULL),
(555, 'Company Profile', 2, 13, 1, 1, 'company-data.php', NULL, NULL),
(556, 'Import / Transfer Data', 2, 13, 1, 1, 'import-shops.php', NULL, NULL),
(9200, 'Data Migration', 2, 13, 1, 1, 'data-migration.php', NULL, NULL),
(557, 'Setup', 2, 13, 1, 1, 'NULL', NULL, NULL),
(558, 'Customer Zone', 2, 13, 1, 1, 'NULL', NULL, NULL),
(559, 'Utilities', 2, 13, 1, 1, 'utilities.php', NULL, NULL),
(560, 'New User Account', 3, 552, 1, 1, 'new-user-account.php', NULL, NULL),
(561, 'Manage user account', 3, 552, 1, 1, 'user-accounts.php', NULL, NULL),
(562, 'User Roles', 3, 552, 1, 1, 'NULL', NULL, NULL),
(563, 'New User role', 3, 552, 1, 1, 'new-user-role.php', NULL, NULL),
(564, 'Manage user role', 3, 552, 1, 1, 'user-role.php', NULL, NULL),
(565, 'User Access Control', 3, 552, 1, 1, 'user-access-control.php', NULL, NULL),
(566, 'Backup Data', 3, 553, 1, 1, 'export-data.php', NULL, NULL),
(567, 'Restore Data', 3, 553, 1, 1, 'import-data.php', NULL, NULL),
(568, 'New Transporter Adda', 3, 554, 1, 1, 'new-transporter.php', NULL, NULL),
(569, 'Manage Transporter Adda', 3, 554, 1, 1, 'transporter-list.php', NULL, NULL),
(570, 'Reports Status', 3, 557, 0, 2, 'NULL', NULL, NULL),
(571, 'Mobile Application Settings', 3, 557, 0, 2, 'sales-app-settings.php', NULL, NULL),
(572, 'Application Access', 3, 557, 0, 2, 'sales-app-menus.php', NULL, NULL),
(573, 'No-Order Reasons', 3, 557, 0, 2, 'NULL', NULL, NULL),
(574, 'New Reason', 3, 557, 0, 2, 'new-no-order-reason.php', NULL, NULL),
(575, 'Manage Reasons', 3, 557, 0, 2, 'noorder-reason-list.php', NULL, NULL),
(576, 'Expense Types', 3, 557, 0, 2, 'NULL', NULL, NULL),
(577, 'New Expense Type', 3, 557, 0, 2, 'new-mexpense-type.php', NULL, NULL),
(578, 'Manage Expense Types', 3, 557, 0, 2, 'mexpense-type-list.php', NULL, NULL),
(579, 'Travelling Expense', 3, 557, 0, 2, 'NULL', NULL, NULL),
(580, 'New Town', 3, 557, 0, 2, 'new-town.php', NULL, NULL),
(581, 'Town List', 3, 557, 0, 2, 'town-list.php', NULL, NULL),
(582, 'Manage Travelling Rate', 3, 557, 0, 2, 'NULL', NULL, NULL),
(583, 'Town Geography', 3, 557, 0, 2, 'NULL', NULL, NULL),
(584, 'New Geography', 3, 557, 0, 2, 'new-town-geo.php', NULL, NULL),
(585, 'Geography List', 3, 557, 0, 2, 'geo-list.php', NULL, NULL),
(586, 'Company Locations', 3, 557, 1, 1, 'NULL', NULL, NULL),
(587, 'New Location', 3, 557, 1, 1, 'new-distributor.php', NULL, NULL),
(589, 'Department', 3, 557, 1, 1, 'NULL', NULL, NULL),
(590, 'New Department', 3, 557, 1, 1, 'new-department.php', NULL, NULL),
(591, 'Manage Department', 3, 557, 1, 1, 'user-department.php', NULL, NULL),
(592, 'Warehouse', 3, 557, 1, 1, 'NULL', NULL, NULL),
(593, 'New Warehouse', 3, 592, 1, 1, 'new-warehouse.php', NULL, NULL),
(594, 'Warehouse List', 3, 592, 1, 1, 'warehouse-list.php', NULL, NULL),
(595, 'Job Designation', 3, 557, 1, 1, 'NULL', NULL, NULL),
(596, 'New Designation', 3, 557, 1, 1, 'new-job-position.php', NULL, NULL),
(597, 'Manage Designation', 3, 557, 1, 1, 'user-position.php', NULL, NULL),
(598, 'New Zone', 3, 558, 1, 1, 'new-customer-zone.php', NULL, NULL),
(599, 'Manage  Zone', 3, 558, 1, 1, 'manage-customer-zone.php', NULL, NULL),
(600, 'New Product', 2, 36, 0, 2, 'new-item.php', NULL, NULL),
(602, 'Product Type', 2, 36, 0, 2, 'NULL', NULL, NULL),
(603, 'Prouct Brand', 2, 36, 0, 2, 'NULL', NULL, NULL),
(604, 'New Product type', 3, 602, 0, 2, 'new-item-type.php', NULL, NULL),
(605, 'Manage product type', 3, 602, 0, 2, 'manage-item-type.php', NULL, NULL),
(606, 'New product brand', 3, 603, 0, 2, 'new-brand.php', NULL, NULL),
(607, 'Manage product brand', 3, 603, 0, 2, 'brand-list.php', NULL, NULL),
(609, 'Booker Sales Report', 2, 17, 0, 2, 'NULL', NULL, NULL),
(610, 'Booker Daily Activity Report', 2, 17, 0, 2, 'NULL', NULL, NULL),
(611, 'Booker Tracking Report', 2, 17, 0, 2, 'NULL', NULL, NULL),
(612, 'Booker Stock Report', 2, 17, 0, 2, 'NULL', NULL, NULL),
(613, 'Booker General Report', 2, 17, 0, 2, 'NULL', NULL, NULL),
(614, 'Doctor Activity Report', 2, 17, 0, 3, 'NULL', NULL, NULL),
(615, 'Medical Rep. Report', 2, 17, 0, 3, 'report-tso-list.php', NULL, NULL),
(616, 'Medical Rep General List Report', 2, 17, 0, 3, 'NULL', NULL, NULL),
(617, 'BA Daily Activity Report', 2, 17, 0, 4, 'NULL', NULL, NULL),
(618, 'Customer Report', 2, 17, 1, 1, 'NULL', NULL, NULL),
(619, 'Expense Report', 2, 17, 1, 1, 'NULL', NULL, NULL),
(620, 'Sales Report', 2, 17, 1, 1, 'NULL', NULL, NULL),
(621, 'Vendor / Supplier Report', 3, 17, 1, 1, 'NULL', NULL, NULL),
(622, 'Memorized Reports', 2, 17, 1, 1, 'NULL', NULL, NULL),
(623, 'General Report', 2, 17, 1, 1, 'NULL', NULL, NULL),
(624, 'Human Resource', 2, 17, 1, 9, 'NULL', NULL, NULL),
(625, 'CRM Report', 2, 17, 1, 7, 'NULL', NULL, NULL),
(626, 'Purchase Report', 2, 17, 1, 1, 'report-brand-wise-purchase.php', NULL, NULL),
(627, 'Product Report', 2, 17, 1, 1, 'NULL', NULL, NULL),
(628, 'Raw Material Report', 2, 17, 1, 12, 'NULL', NULL, NULL),
(948, 'NULL', 3, 0, 0, 14, 'NULL', NULL, NULL),
(947, 'NULL', 3, 0, 0, 14, 'NULL', NULL, NULL),
(946, 'Manage Store Stock', 1, 0, 0, 4, 'NULL', NULL, NULL),
(945, 'Export Packing List', 3, 720, 1, 1, 'export-packing.php', NULL, NULL),
(944, 'Export Detail Report', 3, 720, 1, 1, 'export-detail-report.php', NULL, NULL),
(943, 'Employee(s) Approval Pending', 2, 484, 1, 9, 'employee-list-pending.php', NULL, NULL),
(942, 'Pending Quotation (Notification)', 3, 625, 1, 1, 'NULL', NULL, NULL),
(941, 'Customer credit days (Notification)', 3, 618, 1, 1, 'c-credit-report.php', NULL, NULL),
(940, 'Product below level (Notification)', 3, 627, 1, 1, 'min-inventory-report.php', NULL, NULL),
(939, 'Material below level (Notification)', 3, 628, 0, 1, 'min-material-report.php', NULL, NULL),
(938, 'Daily Production Sheet', 3, 1389, 1, 19, 'report-production-sheet.php', NULL, NULL),
(937, 'Purchase Discount Report', 3, 626, 1, 1, 'NULL', NULL, NULL),
(936, 'Unproductive Shop List', 3, 719, 1, 1, 'load-sheet107.php', NULL, NULL),
(935, 'Shop Merchandising Activity  Summary', 3, 719, 1, 1, 'tso-merchandizing2.php', NULL, NULL),
(934, 'Shop Merchandising Activity', 3, 719, 1, 1, 'tso-merchandizing.php', NULL, NULL),
(933, 'Asset Activity Report', 3, 931, 1, 1, 'warehouse-asset-activity-report.php', NULL, NULL),
(932, 'Asset Activity List', 3, 931, 1, 1, 'asset-activity-list.php', NULL, NULL),
(931, 'Asset Reports', 2, 17, 1, 1, 'NULL', NULL, NULL),
(930, 'Services List', 2, 928, 1, 1, 'manage-services.php', NULL, NULL),
(929, 'New Services', 2, 928, 1, 1, 'new-services.php', NULL, NULL),
(928, 'Services', 1, 0, 1, 1, 'NULL', NULL, NULL),
(927, 'File System', 1, 0, 1, 1, 'NULL', NULL, NULL),
(926, 'Pending Work Order Approval (Purchase)', 2, 8, 1, 1, 'manage-pending-pwoc.php', NULL, NULL),
(925, 'Pending Work Order Approval (Sales)', 2, 8, 1, 1, 'manage-pending-swoc.php', NULL, NULL),
(668, 'New Customer MOQ Profile', 3, 668, 1, 1, 'NULL', NULL, NULL),
(667, 'Customer MOQ Profile', 3, 4, 1, 1, 'NULL', NULL, NULL),
(677, 'Employee Profile', 2, 1, 1, 1, 'NULL', NULL, NULL),
(678, 'Notice Board', 2, 1, 1, 1, 'NULL', NULL, NULL),
(679, 'Attendace Summary', 2, 1, 1, 1, 'NULL', NULL, NULL),
(680, 'Leave Balance', 2, 1, 1, 1, 'NULL', NULL, NULL),
(681, 'Expense Claims', 2, 1, 0, 1, 'NULL', NULL, NULL),
(682, 'Monthly Expense', 2, 1, 1, 1, 'NULL', NULL, NULL),
(683, 'Weekly Sales', 2, 1, 1, 1, 'NULL', NULL, NULL),
(684, 'Top 5 Brands', 2, 1, 0, 1, 'NULL', NULL, NULL),
(685, 'Top 3 Types', 2, 1, 0, 1, 'NULL', NULL, NULL),
(686, 'Stock Threshold', 2, 1, 1, 1, 'NULL', NULL, NULL),
(687, 'Today Sales\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(688, 'Todays Sale Order\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(689, 'Todays Payments Recovery\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(690, 'Todays Return\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(691, 'Todays Purchase\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(692, 'Todays Purchase Order\r\n', 3, 1, 1, 1, 'NULL', NULL, NULL),
(693, 'Total Customers\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(694, 'Total Products\r\n', 2, 1, 1, 1, 'NULL', NULL, NULL),
(695, 'FISCAL YEAR GRAPH', 2, 1, 1, 1, 'NULL', NULL, NULL),
(696, 'Point of Sales ', 1, 0, 1, 11, 'pos/index.php', NULL, NULL),
(697, 'POS Return', 1, 0, 1, 11, 'pos-return.php', NULL, NULL),
(7051, 'RMS Kitchen Orders', 1, 0, 1, 11, 'pos/rms-kitchen.php', NULL, NULL),
(7052, 'RMS Delivery In Process', 1, 0, 1, 11, 'pos/rms-delivery-process.php', NULL, NULL),
(7053, 'RMS Cashier (Rider Return)', 1, 0, 1, 11, 'pos/rms-cashier-return.php', NULL, NULL),
(7054, 'RMS Dine In Console', 1, 0, 1, 11, 'pos/rms-dinein.php', NULL, NULL),
(698, 'HR Request', 1, 0, 1, 1, 'NULL', NULL, NULL),
(699, 'Leaves', 2, 698, 1, 1, 'NULL', NULL, NULL),
(700, 'Half Day', 2, 698, 1, 1, 'NULL', NULL, NULL),
(701, 'Loan &amp; Advances ', 2, 698, 1, 1, 'NULL', NULL, NULL),
(702, 'Promotion &amp; Appraisals', 2, 698, 1, 1, 'NULL', NULL, NULL),
(703, 'Expense Claims', 2, 698, 1, 1, 'NULL', NULL, NULL),
(704, 'Insurance Claims', 2, 698, 1, 1, 'NULL', NULL, NULL),
(705, 'Request Leave', 3, 0, 1, 1, 'NULL', NULL, NULL),
(706, 'Leaves Status', 3, 0, 1, 1, 'NULL', NULL, NULL),
(707, 'Request Half Day', 3, 700, 1, 1, 'new-halfday-request.php', NULL, NULL),
(708, 'Half Day Status', 3, 700, 1, 1, 'halfday-request-status.php', NULL, NULL),
(709, 'Loan &amp; Advances  Request', 3, 0, 1, 1, 'new-loan-request.php', NULL, NULL),
(710, 'Loans &amp; Advances  Status', 3, 0, 1, 1, 'NULL', NULL, NULL),
(711, 'New Appraisal Request', 3, 0, 1, 1, 'new-appraisal-request.php', NULL, NULL),
(712, 'Manage Appraisals Status', 3, 0, 1, 1, 'appraisal-request-status.php', NULL, NULL),
(713, 'Manage Pending Appraisals', 3, 0, 1, 1, 'manage-pending-appraisals.php', NULL, NULL),
(714, 'Expense Request', 3, 0, 1, 1, 'new-expense-request.php', NULL, NULL),
(715, 'Claim Status', 3, 0, 1, 1, 'expense-request-status.php', NULL, NULL),
(716, 'Claim Request', 3, 0, 1, 1, 'new-expense-request.php', NULL, NULL),
(717, 'Claim Status', 3, 0, 1, 1, 'expense-request-status.php', NULL, NULL),
(718, 'Unadjusted Vouchers', 3, 97, 1, 1, 'NULL', NULL, NULL),
(719, 'Salesperson Daily Activity Report', 2, 17, 1, 1, 'NULL', NULL, NULL),
(720, 'Import Reports', 2, 17, 1, 1, 'NULL', NULL, NULL),
(721, 'Salesperson Daily Activity Report (Visual)', 3, 719, 1, 2, 'daily-activity-report2.php', NULL, NULL),
(722, 'Salesperson Last Location Report (Visual)', 3, 719, 1, 2, 'daily-activity-report3.php', NULL, NULL),
(723, 'Mileage Report ', 3, 719, 1, 1, 'report-mileage.php', NULL, NULL) ";
    
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn) );
    
    
    $sql = " INSERT INTO `temp_system_pages` (`id`, `page_label`, `access_heirarchy`, `parent`, `enable`, `type`, `link`, `log_link`, `log_name`) VALUES
(725, 'Salesperson Daily Activity Report (Timestamps)', 3, 719, 1, 1, 'daily-activity-report.php', NULL, NULL),
(726, 'Day Wise Salesperson Summary Report', 3, 719, 1, 1, 'load-sheet105.php', NULL, NULL),
(727, 'Unproductive Shop Visit', 3, 719, 1, 1, 'tso-shop-visit.php', NULL, NULL),
(728, 'Order Load Sheet', 3, 719, 1, 1, 'load-sheet.php', NULL, NULL),
(729, 'BA Attendance Sheet', 3, 617, 1, 1, 'ba-attendance-sheet.php', NULL, NULL),
(730, 'BA Attendance Summary Report', 3, 617, 1, 1, 'ba-attendance-sheet2.php', NULL, NULL),
(731, 'BA Daily Attendance Sheet', 3, 617, 1, 1, 'ba-attendance-sheet3.php', NULL, NULL),
(732, 'Tertiary Sales Sheet', 3, 617, 1, 1, 'product-wise-sales6.php', NULL, NULL),
(733, 'Tertiary Sales Report', 3, 617, 1, 1, 'report-tertiary.php', NULL, NULL),
(734, 'Product Wise Tertiary Sales', 3, 617, 1, 1, 'NULL', NULL, NULL),
(735, 'BA Daily Sales Sheet', 3, 617, 1, 1, 'ba-sales-sheet3.php', NULL, NULL),
(736, 'BA Daily Sales and Attendance Sheet', 3, 617, 1, 1, 'ba-attendance-sales-sheet4.php', NULL, NULL),
(737, 'BA Sales and Attendance Summary Sheet', 3, 617, 1, 1, 'ba-attendance-sales-sheet4.php', NULL, NULL),
(738, 'Product Wise Sales Report', 3, 617, 1, 1, 'NULL', NULL, NULL),
(739, 'Merchandising Activity', 3, 617, 1, 1, 'ba-merchandizing.php', NULL, NULL),
(740, 'BA Stores Survey Report', 3, 617, 1, 1, 'daily-activity-report51.php', NULL, NULL),
(741, 'Stores Stock Summary Report', 3, 617, 1, 1, 'warehouse-unit-activity-report2.php', NULL, NULL),
(742, 'Stores Stock Activity Report', 3, 617, 1, 1, 'store-stock-activity-report.php', NULL, NULL),
(743, 'Stores Product Stock Report', 3, 617, 1, 1, 'customer-product-stock-summary.php', NULL, NULL),
(744, 'Stores MOQ Profile Summary', 3, 617, 1, 1, 'NULL', NULL, NULL),
(745, 'Stores Product FOC Report', 3, 617, 1, 1, 'customer-product-foc-summary.php', NULL, NULL),
(746, 'Stores Brand Salesperson List', 3, 617, 1, 1, 'customer-brand-salesperson-summary.php', NULL, NULL),
(747, 'Route Wise Load Sheet', 3, 620, 1, 1, 'NULL', NULL, NULL),
(748, 'Sales List Report', 3, 620, 1, 1, 'report-sales.php', NULL, NULL),
(749, 'Sales Report', 3, 620, 1, 1, 'report-brand-wise-sales.php', NULL, NULL),
(750, 'Sales Journal', 3, 620, 1, 1, 'sales-journal.php', NULL, NULL),
(751, 'Net Sales Summary Report', 3, 620, 1, 1, 'report-net-sales.php', NULL, NULL),
(752, 'Sales Return Report', 3, 620, 1, 1, 'report-brand-wise-sales-return.php', NULL, NULL),
(753, 'Sales Return Journal', 3, 620, 1, 1, 'reports/sales-return-journal.php', NULL, NULL),
(754, 'Sales Value Report', 3, 620, 1, 1, 'report-sales-value.php', NULL, NULL),
(755, 'Custom Sales Tax Report', 3, 620, 1, 1, 'sales-tax-custom-report.php', NULL, NULL),
(756, 'Product Sales Summary', 3, 620, 1, 1, 'item-sales-summary.php', NULL, NULL),
(757, 'Stores Brand Sales Summary', 3, 620, 1, 1, 'customer-brand-sales-summary.php', NULL, NULL),
(758, 'Brand Wise Aging Report', 3, 620, 1, 1, 'report-brand-wise-aging.php', NULL, NULL),
(759, 'Order Traceability Report', 3, 620, 1, 1, 'report-order-traceability.php', NULL, NULL),
(760, 'Month Wise Sales Report', 3, 620, 1, 1, 'report-month-wise-sales.php', NULL, NULL),
(761, 'Recovery Report', 3, 620, 1, 1, 'report-recovery.php', NULL, NULL),
(762, 'Sale Order Status Report', 3, 620, 1, 1, 'report-so-summary.php', NULL, NULL),
(763, 'Sale Order Comparison Report', 3, 620, 1, 1, 'report-so-comparison.php', NULL, NULL),
(764, 'Pending Sales Payments', 3, 620, 1, 1, 'sales-pending-payments.php', NULL, NULL),
(765, 'Sales Return Report', 3, 620, 1, 1, 'report-brand-wise-sales-return.php', NULL, NULL),
(766, 'Discounted Sales Report', 3, 620, 1, 1, 'report-discounted-sales.php', NULL, NULL),
(767, 'Debit Note List', 3, 620, 1, 1, 'report-sales-debit-note.php', NULL, NULL),
(768, 'Credit Note List', 3, 620, 1, 1, 'report-sales-credit-note.php', NULL, NULL),
(769, 'Sales Dispatch Report', 3, 620, 1, 1, 'sales-dispatch.php', NULL, NULL),
(770, 'Sales Dispatch Report (Date wise)', 3, 620, 1, 1, 'sales-dispatch2.php', NULL, NULL),
(771, 'Sales Price History Report', 3, 620, 1, 1, 'report-sales-price-history.php', NULL, NULL),
(772, 'Import Detail Report', 3, 720, 1, 1, 'NULL', NULL, NULL),
(773, 'Import Packing List', 3, 720, 1, 1, 'NULL', NULL, NULL),
(774, 'Import Costing Report', 3, 720, 1, 1, 'NULL', NULL, NULL),
(775, 'Purchase Report', 3, 626, 1, 1, 'report-brand-wise-purchase.php', NULL, NULL),
(776, 'Purchase Journal', 3, 626, 1, 1, 'reports/purchase-journal.php', NULL, NULL),
(777, 'Purchase Traceability Report', 3, 626, 1, 1, 'report-purchase-traceability.php', NULL, NULL),
(778, 'Purchase Return Report', 3, 626, 1, 1, 'report-purchase-return.php', NULL, NULL),
(779, 'Purchase List Report', 3, 626, 1, 1, 'report-purchase.php', NULL, NULL),
(780, 'Purchase Return Report', 3, 626, 1, 1, 'report-purchase-return.php', NULL, NULL),
(781, 'Pending Purchase Payments', 3, 626, 1, 1, 'purchase-pending-payments.php', NULL, NULL),
(782, 'Debit Note List', 3, 626, 1, 1, 'report-purchase-debit-note.php', NULL, NULL),
(783, 'Credit Note List', 3, 626, 1, 1, 'report-purchase-credit-note.php', NULL, NULL),
(784, 'Purchase Price History Report', 3, 626, 1, 1, 'report-purchase-price-history.php', NULL, NULL),
(785, 'Product List Report', 3, 627, 1, 1, 'report-item-list.php', NULL, NULL),
(786, 'Product Valuation', 3, 627, 1, 1, 'report-warehouse-inventory-valuation.php', NULL, NULL),
(787, 'Closing Stock Report', 3, 627, 1, 1, 'report-warehouse-inventory-valuation2.php', NULL, NULL),
(788, 'Warehouse Wise Stock Report', 3, 627, 1, 1, 'report-warehouse-inventory-valuation5.php', NULL, NULL),
(789, 'Warehouse Stock Summary Report', 3, 627, 1, 1, 'report-warehouse-inventory-valuation6.php', NULL, NULL),
(790, 'Unit Activity Report', 3, 627, 1, 1, 'dwarehouse-unit-activity-report.php', NULL, NULL),
(791, 'Stock Movement Report', 3, 627, 1, 1, 'warehouse-unit-activity-summary.php', NULL, NULL),
(792, 'Unit Activity List', 3, 627, 1, 1, 'dunit-activity-list.php', NULL, NULL),
(793, 'Warehouse Product Transfer List', 3, 627, 1, 1, 'warehouse-stock-transfer-list.php', NULL, NULL),
(794, 'Product Vendor List', 3, 627, 1, 1, 'report-item-vendor-list.php', NULL, NULL),
(795, 'Cost Adjustment History', 3, 627, 1, 1, 'cost-adjustment-history.php', NULL, NULL),
(796, 'Quantity Adjustment History', 3, 627, 1, 1, 'quantity-adjustment-history.php', NULL, NULL),
(797, 'Product Type List', 3, 627, 1, 1, 'manage-item-type.php', NULL, NULL),
(798, 'Product Brands List', 3, 627, 1, 1, 'brand-list.php', NULL, NULL),
(799, 'Stores List', 3, 618, 1, 1, 'report-customer-list.php', NULL, NULL),
(800, 'Sub Stores List', 3, 618, 1, 1, 'report-customer-sublist.php', NULL, NULL),
(801, 'Stores Activity', 3, 618, 1, 1, 'report-customer-activity.php', NULL, NULL),
(802, 'Customer  Ledger Item wise', 3, 618, 1, 1, 'customer-ledger-item-wise.php', NULL, NULL),
(804, 'Receipt Register', 3, 618, 1, 1, 'report-receipt-register.php', NULL, NULL),
(805, 'Receipt Summary', 3, 618, 1, 1, 'report-receipt-summary.php', NULL, NULL),
(806, 'Stores Sales report', 3, 618, 1, 1, 'report-sales.php', NULL, NULL),
(807, 'Stores Return report', 3, 618, 1, 1, 'report-sales-return.php', NULL, NULL),
(808, 'Most Frequent Stores', 3, 618, 1, 1, 'report-most-frequent-customers.php', NULL, NULL),
(809, 'Stores with no purchase', 3, 618, 1, 1, 'report-customer-no-purchase.php', NULL, NULL),
(810, 'Pending Payments (Sales)', 3, 618, 1, 1, 'sales-pending-payments.php', NULL, NULL),
(811, 'Stores Type Price List (Custom)', 3, 618, 1, 1, 'report-cb-price-custom.php', NULL, NULL),
(812, 'Principle List', 3, 621, 1, 1, 'report-vendor-list.php', NULL, NULL),
(813, 'Principle Activity', 3, 621, 1, 1, 'report-vendor-activity.php', NULL, NULL),
(814, 'Principle Ledger', 3, 621, 1, 1, 'vendor-ledger.php', NULL, NULL),
(815, 'Aging Payable', 3, 621, 1, 1, 'v-aging-report.php', NULL, NULL),
(816, 'Payment Register', 3, 621, 1, 1, 'report-payment-register.php', NULL, NULL),
(817, 'Payment Summary', 3, 621, 1, 1, 'report-payment-summary.php', NULL, NULL),
(818, 'Principle Purchase Report', 3, 621, 1, 1, 'report-purchase.php', NULL, NULL),
(819, 'Most Frequent Vendors', 3, 621, 1, 1, 'report-most-frequent-vendors.php', NULL, NULL),
(820, 'Principle Products List', 3, 621, 1, 1, 'report-vendor-product-list.php', NULL, NULL),
(821, 'Principle Return Report', 3, 621, 1, 1, 'report-purchase-return.php', NULL, NULL),
(822, 'Pending Payment (Purchase)', 3, 621, 1, 1, 'purchase-pending-payments.php', NULL, NULL),
(823, 'Employee Detail List', 3, 624, 1, 9, 'report-employee-details2.php', NULL, NULL),
(824, 'Employee Daily Attendance Sheet', 3, 624, 1, 9, 'report-employee-clockin.php', NULL, NULL),
(825, 'Employee Time sheet report', 3, 624, 1, 9, 'report-employee-clockin.php', NULL, NULL),
(826, 'Employee Time sheet (Machine Raw Format)', 3, 624, 1, 9, 'report-employee-clockin3.php', NULL, NULL),
(827, 'Employee Issued Payroll Report', 3, 624, 1, 9, 'report-employee-salary.php', NULL, NULL),
(828, 'Employee Current Payroll Sheet', 3, 624, 1, 9, 'report-employee-salary2.php', NULL, NULL),
(829, 'Employee Performance Summany Report', 3, 624, 1, 9, 'report-employee-assessment-summary.php', NULL, NULL),
(830, 'Employee Detail Report', 3, 624, 1, 9, 'NULL', NULL, NULL),
(831, 'Employee Performance Assessment Report', 3, 624, 1, 9, 'report-employee-assessment.php', NULL, NULL),
(5304, 'Attendance Discrepancy Report', 3, 624, 1, 9, 'report-attendance-discrepancy.php', NULL, NULL),
(832, 'Employee Leaves Detail Report', 3, 624, 1, 9, 'report-employee-leaves.php', NULL, NULL),
(833, 'Employee Pending Appraisals Report', 3, 624, 1, 9, 'report-employee-pending-appraisal.php', NULL, NULL),
(834, 'Employee Bulk Performance Assessment  Request  Report', 3, 624, 1, 9, 'report-employee-bulk-assessment.php', NULL, NULL),
(835, 'Employee Loans & Advance Report', 3, 624, 1, 9, 'report-employee-loan-advance.php', NULL, NULL),
(836, 'Employee Sales Report', 3, 624, 1, 9, 'report-employee-sales.php', NULL, NULL),
(837, 'Employee Commission Earned Report', 3, 624, 1, 9, 'report-employee-commission-earned.php', NULL, NULL),
(838, 'Top 10 Employees (Sales Based) report', 3, 624, 1, 9, 'report-top-10-employee-sales.php', NULL, NULL),
(839, 'Top 10 Employees (Hourly Based) report', 3, 624, 1, 9, 'report-top-10-employee-hourly.php', NULL, NULL),
(840, 'Expense Principle Ledger', 3, 619, 1, 1, 'NULL', NULL, NULL),
(841, 'Expense Detail Report', 3, 619, 1, 1, 'NULL', NULL, NULL),
(842, 'Expense Type Report', 3, 619, 1, 1, 'NULL', NULL, NULL),
(843, 'Recurring Expense List', 3, 619, 1, 1, 'NULL', NULL, NULL),
(844, 'Best 10 Selling Items', 3, 622, 1, 1, 'report-best-selling-items.php', NULL, NULL),
(845, 'Worst 10 Selling Items', 3, 622, 1, 1, 'report-worst-selling-items.php', NULL, NULL),
(846, 'Best 10 Item Brands', 3, 622, 1, 1, 'report-best-selling-brand.php', NULL, NULL),
(847, 'Worst 10 Item Brands', 3, 622, 1, 1, 'report-worst-selling-brand.php', NULL, NULL),
(848, 'Best 10 Item Types', 3, 622, 1, 1, 'report-best-selling-item-type.php', NULL, NULL),
(849, 'Worst 10 Item Types', 3, 622, 1, 1, 'report-worst-selling-item-type.php', NULL, NULL),
(850, 'Most Common Returns', 3, 622, 1, 1, 'report-most-common-returns.php', NULL, NULL),
(851, 'Income Statement', 3, 623, 1, 1, 'income-statement.php', NULL, NULL),
(852, 'Profit & Loss Statement', 3, 623, 1, 1, 'report-profit-report.php', NULL, NULL),
(853, 'Item Profitability Report', 3, 623, 1, 1, 'item-profitability-report.php', NULL, NULL),
(854, 'Company Assets', 3, 623, 1, 1, 'NULL', NULL, NULL),
(855, 'System Audit Trail', 3, 623, 1, 1, 'audit-trail.php', NULL, NULL),
(856, 'Order Load Sheet', 3, 608, 1, 1, 'load-sheet.php', NULL, NULL),
(862, 'DSR Report', 3, 608, 1, 1, 'dsr-sheet.php', NULL, NULL),
-- (863, 'Master Sales Report', 3, 608, 1, 1, 'master-sales-report.php', NULL, NULL),
-- (864, 'Sales Analysis Report', 3, 608, 1, 1, 'NULL', NULL, NULL),
-- (865, 'Booking vs Execution (Order Wise)', 3, 608, 1, 1, 'delivery-order-report.php', NULL, NULL),
-- (866, 'Daily Activity Report', 3, 608, 1, 1, 'salesman-daily-activity.php', NULL, NULL),
-- (867, 'Operation Monitoring Report', 3, 608, 1, 1, 'load-sheet998.php', NULL, NULL),
 (868, 'Order Location Report', 3, 611, 1, 1, 'delivery-location-report.php', NULL, NULL),
(869, 'Check In Report', 3, 611, 1, 1, 'checkin-report.php', NULL, NULL),
-- (870, 'Mileage Report', 3, 611, 1, 1, 'report-mileage.php', NULL, NULL),
(871, 'TSO Daily Activity Report (Visual)', 3, 611, 1, 1, 'daily-activity-report2.php', NULL, NULL),
(872, 'TSO Last Activity Report (Visual)', 3, 611, 1, 2, 'daily-activity-report5.php', NULL, NULL),
(873, 'TSO Last Location Report (Visual)', 3, 611, 1, 1, 'daily-activity-report3.php', NULL, NULL),
(874, 'TSO Shortest Route Report', 3, 611, 1, 2, 'daily-activity-report4.php', NULL, NULL),
(875, 'Order Visual Location Report', 3, 611, 1, 1, 'order-visual-tracking-report.php', NULL, NULL),
(876, 'Shop Location Report', 3, 611, 1, 1, 'NULL', NULL, NULL),
(877, 'Visual Tracking Report', 3, 611, 1, 1, 'visual-tracking-report.php', NULL, NULL),



(885, 'TSO Cancelleded Orders Report', 3, 609, 1, 1, 'load-sheet101.php', NULL, NULL),
(887, 'TSO Sales Recovery Report', 3, 609, 1, 1, 'load-sheet103.php', NULL, NULL),
-- (888, 'Route Wise Sales Report', 3, 609, 1, 1, 'NULL', NULL, NULL),
-- (889, 'Area Wise Sales Report', 3, 609, 1, 1, 'area-wise-sales.php', NULL, NULL),
-- (890, 'Area Based Visual Report', 3, 609, 1, 1, 'area-based-visual-report.php', NULL, NULL),
-- (891, 'TSO Progress Report', 3, 609, 1, 1, 'salesman-wise-sales.php', NULL, NULL),
-- (892, 'TSO Progress Visual Report', 3, 609, 1, 1, 'salesman-wise-sales2.php', NULL, NULL),
-- (893, 'Shop Wise Sales Report', 3, 609, 1, 1, 'shop-wise-sales.php', NULL, NULL),
-- (894, 'Shop Wise Credit Report', 3, 609, 1, 1, 'shop-wise-credit.php', NULL, NULL),
-- (895, 'Sales Summary Report', 3, 609, 1, 1, 'load-sheet6.php', NULL, NULL),
-- (896, 'Sales Detail Report', 3, 609, 1, 1, 'load-sheet66.php', NULL, NULL),
(897, 'Sales Return Report', 3, 609, 1, 1, 'report-brand-wise-sales-return.php', NULL, NULL),
-- (898, 'Sales Trend Report', 3, 609, 1, 1, 'load-sheet8.php', NULL, NULL),
-- (899, 'Shop Ledger', 3, 609, 1, 1, 'load-sheets1.php', NULL, NULL),
-- (901, 'Inventory Valuation (Warehouse)', 3, 612, 1, 1, 'report-warehouse-inventory-valuation.php', NULL, NULL),
(902, 'Unit Activity Report', 3, 612, 1, 1, 'dwarehouse-unit-activity-report.php', NULL, NULL),
(903, 'Unit Activity List', 3, 612, 1, 1, 'dunit-activity-list.php', NULL, NULL),
(904, 'Shop Stock Report', 3, 612, 1, 1, 'NULL', NULL, NULL),
-- (905, 'TSO Attendance Sheet', 3, 610, 1, 1, 'tso-attendance-sheet.php', NULL, NULL),
-- (906, 'TSO Attendance Summary Report', 3, 610, 1, 1, 'tso-attendance-sheet2.php', NULL, NULL),
(907, 'TSO Daily Attendance Sheet', 3, 610, 1, 1, 'NULL', NULL, NULL),
(908, 'TSO Unproductive Visit Report', 3, 610, 1, 1, 'tso-shop-visit.php', NULL, NULL),
-- (910, 'TSO Daily Activity Report (Timestamps)', 3, 610, 1, 1, 'daily-activity-report.php', NULL, NULL),
-- (911, 'TSO Target Report', 3, 610, 1, 1, 'salesman-wise-target.php', NULL, NULL),
(912, 'Order Execution Pending Report', 3, 613, 1, 1, 'report-pending-order-execution.php', NULL, NULL),
(913, 'Return Execution Pending Report', 3, 613, 1, 1, 'report-pending-return-execution.php', NULL, NULL),
(914, 'Shop Route Mapping Report', 3, 613, 1, 1, 'NULL', NULL, NULL),
(915, 'Route Area Mapping Report', 3, 613, 1, 1, 'report-pending-route-area.php', NULL, NULL),
(916, 'System Log Report', 3, 613, 1, 1, 'NULL', NULL, NULL),
(917, 'Phone Status Report', 3, 613, 1, 1, 'report-salesman-phone.php', NULL, NULL),
(918, 'TSO Last Update Report', 3, 613, 1, 1, 'report-last-update.php', NULL, NULL),
(919, 'Shop List', 3, 613, 1, 1, 'report-salesman-shop.php', NULL, NULL),
(921, 'Distributor List', 3, 613, 1, 1, 'report-distributor-list.php', NULL, NULL),
(922, 'TSO List', 3, 613, 1, 1, 'report-tso-list.php', NULL, NULL),
(923, 'Routes List', 3, 613, 1, 1, 'route-list.php', NULL, NULL),
(924, 'Areas List', 3, 613, 1, 1, 'report-area-list.php', NULL, NULL),
(949, 'Top 3 Brands (S &amp; D)', 2, 1, 0, 2, 'NULL', NULL, NULL),
(950, 'Top 3 Distributor', 2, 1, 0, 2, 'NULL', NULL, NULL),
(951, 'Top 3 Products', 2, 1, 0, 2, 'NULL', NULL, NULL),
(952, 'Top 3 Item TYPES', 2, 1, 0, 2, 'NULL', NULL, NULL),
(953, 'Total TSO', 2, 1, 0, 2, 'NULL', NULL, NULL),
(954, 'Booking Today', 2, 1, 0, 2, 'NULL', NULL, NULL),
(955, 'Sales Yesterday', 2, 1, 0, 2, 'NULL', NULL, NULL),
(956, 'Total Shop', 2, 1, 0, 2, 'NULL', NULL, NULL),
(957, 'Sales Current Month', 2, 1, 0, 2, 'NULL', NULL, NULL),
(958, 'Unit Sold', 2, 1, 0, 2, 'NULL', NULL, NULL),
(959, 'Sales Previous Month', 2, 1, 0, 2, 'NULL', NULL, NULL),
(960, 'Fiscal Year Sales Graph', 2, 1, 0, 2, 'NULL', NULL, NULL),
(961, 'System Activity', 2, 1, 0, 2, 'NULL', NULL, NULL),
(632, 'Daily Booking Value Summary', 3, 608, 0, 2, 'load-sheet99.php', NULL, NULL),
(631, 'Salesman Delivery List', 3, 608, 0, 2, 'delivery-report.php', NULL, NULL),
(630, 'Salesman Delivery Sheet', 3, 608, 0, 2, 'load-sheet991.php', NULL, NULL),
-- (629, 'Order Load Sheet', 3, 608, 0, 2, 'load-sheet.php', NULL, NULL),
(633, 'Non Dispatch Order Report', 3, 608, 0, 2, 'load-sheet3.php', NULL, NULL),
(634, 'Order vs Execution Report', 3, 608, 0, 2, 'load-sheet5.php', NULL, NULL),
(635, 'DSR Report', 3, 608, 0, 2, 'dsr-sheet.php', NULL, NULL),
(636, 'Master Sales Report', 3, 608, 0, 2, 'master-sales-report.php', NULL, NULL),
(637, 'Sales Analysis Report', 3, 608, 0, 2, 'NULL', NULL, NULL),
(638, 'Booking vs Execution (Order Wise)', 3, 608, 0, 2, 'delivery-order-report.php', NULL, NULL),
(639, 'Daily Activity Report', 3, 608, 0, 2, 'salesman-daily-activity.php', NULL, NULL),
(640, 'Operation Monitoring Report', 3, 608, 0, 2, 'load-sheet998.php', NULL, NULL),
(641, 'Product Wise Sales Report', 3, 609, 0, 2, 'NULL', NULL, NULL),
-- (642, 'Unproductive Shop List', 3, 609, 0, 2, 'load-sheet107.php', NULL, NULL),
(643, 'TSO Daily Activity Report', 3, 609, 0, 2, 'salesman-productivity.php', NULL, NULL),
(644, 'Manager Wise DSR Report', 3, 609, 0, 2, 'NULL', NULL, NULL),
(645, 'Last Execution Report', 3, 609, 0, 2, 'load-sheet104.php', NULL, NULL),
(646, 'Day Wise TSO Summary Report', 3, 609, 0, 2, 'load-sheet105.php', NULL, NULL),
(647, 'TSO Daily Route Plan Report', 3, 609, 0, 2, 'salesman-route-plan.php', NULL, NULL),
(651, 'TSO Cancelled Order Report', 3, 609, 0, 2, 'load-sheet101.php', NULL, NULL),
(652, 'TSO Sales Return Report', 3, 609, 0, 2, 'load-sheet102.php', NULL, NULL),
(653, 'TSO Sales Recovery Report', 3, 609, 0, 2, 'load-sheet103.php', NULL, NULL),
(654, 'Route Wise Sales Report', 3, 609, 0, 2, 'NULL', NULL, NULL),
(655, 'Area Wise Sales Report', 3, 609, 0, 2, 'area-wise-sales.php', NULL, NULL),
(656, 'Area Based Visual Report', 3, 609, 0, 2, 'area-based-visual-report.php', NULL, NULL),
(657, 'TSO Progress Report', 3, 609, 0, 2, 'salesman-wise-sales.php', NULL, NULL),
(658, 'TSO Progress Visual Report', 3, 609, 0, 2, 'salesman-wise-sales2.php', NULL, NULL),
(659, 'Shop Wise Sales Report', 3, 609, 0, 2, 'shop-wise-sales.php', NULL, NULL),
(660, 'Shop Wise Credit Report', 3, 609, 0, 2, 'shop-wise-credit.php', NULL, NULL),
(661, 'Sales Summary Report', 3, 609, 0, 2, 'load-sheet6.php', NULL, NULL),
(662, 'Sales Detail Report', 3, 609, 0, 2, 'load-sheet66.php', NULL, NULL),
(663, 'Sales Return Report', 3, 609, 0, 1, 'report-brand-wise-sales-return.php', NULL, NULL),
(664, 'Sales Trend Report', 3, 609, 0, 2, 'load-sheet8.php', NULL, NULL),
(665, 'Shop Ledger', 3, 609, 0, 2, 'load-sheets1.php', NULL, NULL),
(666, 'Aging Report', 3, 609, 0, 2, 's-aging-report.php', NULL, NULL),
(962, 'TSO Attendance Sheet', 3, 610, 0, 2, 'tso-attendance-sheet.php', NULL, NULL),
(963, 'TSO Attendance Summary Report', 3, 610, 0, 2, 'tso-attendance-sheet2.php', NULL, NULL),
(964, 'BA Daily Attendance Sheet', 3, 610, 0, 2, 'ba-attendance-sheet3.php', NULL, NULL),
(965, 'TSO Unproductive Visit Report', 3, 610, 0, 2, 'tso-shop-visit.php', NULL, NULL),
(967, 'Shop Merchandising Activity', 3, 610, 0, 2, 'tso-merchandizing.php', NULL, NULL),
(968, 'Shop Merchandising Activity Summary', 3, 610, 0, 2, 'tso-merchandizing2.php', NULL, NULL),
(969, 'TSO Daily Activity Report (Timestamps)', 3, 610, 0, 2, 'daily-activity-report.php', NULL, NULL),
-- (970, 'TSO Target Report', 3, 610, 0, 2, 'salesman-wise-target.php', NULL, NULL),
-- (971, 'Order Location Report', 3, 611, 0, 2, 'delivery-location-report.php', NULL, NULL),
(972, 'Check In Report', 3, 611, 0, 2, 'checkin-report.php', NULL, NULL),
-- (973, 'Mileage Report', 3, 611, 0, 2, 'report-mileage.php', NULL, NULL),
(974, 'TSO Daily Activity Report (Visual)', 3, 611, 0, 2, 'daily-activity-report2.php', NULL, NULL),
(975, 'TSO Last Activity Report (Visual)', 3, 611, 0, 2, 'daily-activity-report5.php', NULL, NULL),
(976, 'TSO Last Location Report (Visual)', 3, 611, 0, 2, 'daily-activity-report3.php', NULL, NULL),
-- (977, 'TSO Shortest Route Report', 3, 611, 0, 2, 'daily-activity-report4.php', NULL, NULL),
(978, 'Order Visual Location Report', 3, 611, 0, 2, 'order-visual-tracking-report.php', NULL, NULL),
(979, 'Shop Location Report', 3, 611, 0, 2, 'NULL', NULL, NULL),
-- (980, 'Visual Tracking Report', 3, 611, 0, 2, 'visual-tracking-report.php', NULL, NULL),
(981, 'Inventory Valuation (Warehouse)', 3, 612, 0, 2, 'report-dwarehouse-inventory-valuation.php', NULL, NULL),
(982, 'Unit Activity Report', 3, 612, 0, 2, 'dwarehouse-unit-activity-report.php', NULL, NULL),
(983, 'Unit Activity List', 3, 612, 0, 2, 'dunit-activity-list.php', NULL, NULL),
-- (984, 'Shop Stock Report', 3, 612, 0, 2, 'NULL', NULL, NULL),
-- (985, 'Order Execution Pending Report', 3, 613, 0, 2, 'report-pending-order-execution.php', NULL, NULL),
-- (986, 'Return Execution Pending Report', 3, 613, 0, 2, 'report-pending-return-execution.php', NULL, NULL),
(987, 'Shop Route Mapping Report', 3, 613, 0, 2, 'NULL', NULL, NULL),
(988, 'Route Area Mapping Report', 3, 613, 0, 2, 'report-pending-route-area.php', NULL, NULL),
(989, 'System Log Report', 3, 613, 0, 2, 'NULL', NULL, NULL),
(990, 'TSO Support Status Report', 3, 613, 0, 2, 'tso-support.php', NULL, NULL),
(991, 'Phone Status Report', 3, 613, 0, 2, 'report-salesman-phone.php', NULL, NULL),
-- (992, 'TSO Last Update Report', 3, 613, 0, 2, 'report-last-update.php', NULL, NULL),
(993, 'Shop List', 3, 613, 0, 2, 'report-salesman-shop.php', NULL, NULL),
(994, 'Product List Report 2', 3, 613, 0, 2, 'report-item-list2.php', NULL, NULL),
(996, 'TSO List', 3, 613, 0, 2, 'report-tso-list.php', NULL, NULL),
(997, 'Route List', 3, 613, 0, 2, 'route-list.php', NULL, NULL),
(998, 'Areas List', 3, 613, 0, 2, 'report-area-list.php', NULL, NULL),
(999, 'Raw Material List', 3, 628, 1, 1, 'report-rm-list.php', NULL, NULL),
(1000, 'Raw Material Stock Valuation', 3, 628, 1, 1, 'report-warehouse-rm-valuation.php', NULL, NULL),
(1001, 'Raw Material Activity Report', 3, 628, 1, 1, 'warehouse-rm-activity-report.php', NULL, NULL),
(1002, 'Raw Material Activity List', 3, 628, 1, 1, 'rm-activity-list.php', NULL, NULL),
(1003, 'Warehouse Raw Material Transfer  List', 3, 628, 1, 1, 'warehouse-stock-transfer-listc.php', NULL, NULL),
(1004, 'Stock Aging Report', 3, 628, 1, 1, 'NULL', NULL, NULL),
(1005, 'Stores Brand Tertiary Sales', 3, 617, 1, 1, 'NULL', NULL, NULL),
(1006, 'File System', 3, 0, 1, 26, 'NULL', NULL, NULL),
(1007, 'New File System', 3, 1006, 1, 26, 'new-file-system.php', NULL, NULL),
(1008, 'Manage File System', 3, 1006, 1, 26, 'manage-file-system.php', NULL, NULL),
(1009, 'Import Internal Costing', 3, 1006, 1, 26, 'import-internal-cost.php', NULL, NULL),
(1010, 'Pending LPR Issuance', 3, 1006, 1, 26, 'manage-pending-lpr.php', NULL, NULL),
(1011, 'Shop Wise Monthly Sales Report', 3, 609, 0, 2, 'NULL', NULL, NULL),
(1012, 'Store MOQ List Report', 3, 617, 1, 1, 'NULL', NULL, NULL),
(1013, 'Progress Status', 1, 0, 0, 2, 'NULL', NULL, NULL),
(1014, 'Import / Update Products', 2, 2, 1, 1, 'import-products2.php', NULL, NULL),
(1015, 'New Customer Category', 3, 371, 1, 1, 'new-customer-type.php', NULL, NULL),
(1016, 'Manage Customer Category', 3, 371, 1, 1, 'NULL', NULL, NULL),
(1017, 'New Customer Sub Category ', 3, 372, 1, 1, 'NULL', NULL, NULL),
(1018, 'Manage Customer Sub Category', 3, 372, 1, 1, 'NULL', NULL, NULL),
(1019, 'New Customer Slab', 3, 370, 1, 1, 'NULL', NULL, NULL),
(1020, 'Manage Customer Slab', 3, 370, 1, 1, 'NULL', NULL, NULL),
(1021, 'Assign Project Manager', 3, 1006, 1, 26, 'project-pending-manager.php', NULL, NULL),
(1022, 'Assign Project Supervisor', 3, 1006, 1, 26, 'project-supervisor.php', NULL, NULL),
(1023, 'Pending LPR Return', 3, 1006, 1, 26, 'manage-pending-rlpr.php', NULL, NULL),
(1024, 'Purchase Requisition ', 3, 0, 0, 13, 'manage-pr.php', NULL, NULL),
(1025, 'New Requisition ', 3, 1024, 0, 13, 'NULL', NULL, NULL),
(1026, 'Manage Requisition', 3, 1024, 0, 13, 'NULL', NULL, NULL),
(1027, 'Manage Pending Projects', 3, 1006, 1, 26, 'manage-pending-project.php', NULL, NULL),
(1028, 'Project Checklist', 3, 0, 1, 9, 'NULL', NULL, NULL),
(1030, 'Pending Checklist', 3, 1028, 1, 9, 'NULL', NULL, NULL),
(1029, 'Manage Checklist', 3, 1028, 1, 9, 'project-checklist.php', NULL, NULL),
(1031, 'Manage Pending  LPR', 3, 1006, 1, 26, 'manage-pending-lpr.php', NULL, NULL),
(1032, 'Manage Pending Internal Cost', 3, 1006, 1, 26, 'NULL', NULL, NULL),
(1033, 'Project Directory', 3, 1006, 1, 26, 'project-directory.php', NULL, NULL),
(1034, 'Project Elements', 3, 1006, 1, 26, 'manage-project-cost2.php', NULL, NULL),
(1037, 'Project Completion (Operation)', 3, 1006, 1, 26, 'project-completion.php', NULL, NULL),
(1038, 'Project Completion (Client Servicing)', 3, 1006, 1, 26, 'projectc-completion.php', NULL, NULL),
(1039, 'Project Completion (Finance)', 3, 1006, 1, 26, 'projectf-completion.php', NULL, NULL),
(1041, 'Item Stock Inquiry', 3, 1006, 1, 26, 'inventory-inquery.php', NULL, NULL),
(1042, 'Project List (Client Servicing)', 3, 1006, 1, 26, 'NULL', NULL, NULL),
(1043, 'Lead Detail Report', 3, 625, 1, 7, 'report-lead-detail.php', NULL, NULL),
(1044, 'Lead Summary Report', 3, 625, 1, 7, 'report-lead-details.php', NULL, NULL),
(1045, 'Lead Funnel Report', 3, 625, 1, 7, 'report-lead-graph.php', NULL, NULL),
(1046, 'Follow Up Report', 3, 625, 1, 7, 'report-followup.php', NULL, NULL),
(1047, 'Customer Enquiry Report ', 3, 625, 1, 7, 'NULL', NULL, NULL),
(1048, 'Quotation Report', 3, 625, 1, 7, 'report-quotation-detail.php', NULL, NULL),
(1049, 'Item Stock Inquiry', 3, 1640, 1, 15, 'inventory-inquery.php', NULL, NULL),
(1050, 'Stock Issuance List', 3, 0, 1, 15, 'NULL', NULL, NULL),
(1051, 'Stock Requisition', 3, 0, 1, 15, 'new-issue-request.php', NULL, NULL),
(1052, 'Stock Return', 3, 0, 1, 15, 'NULL', NULL, NULL),
(1053, 'Manage Store', 3, 0, 1, 15, 'NULL', NULL, NULL),
(1054, 'New Issue Request', 3, 1051, 1, 15, 'new-issue-request.php', NULL, NULL),
(1055, 'Issue Request List', 3, 1051, 1, 15, 'stock-issuance-list.php', NULL, NULL),
(1056, 'Issue Request Pending  List (Department)', 3, 1051, 0, 15, 'issue-pending-dept-lists.php', NULL, NULL),
(1057, 'New Return Request', 3, 1052, 1, 15, 'new-return-request.php', NULL, NULL),
(1058, 'Return Request List', 3, 1052, 1, 15, 'return-requestion-list.php', NULL, NULL),
(1059, 'New Issue  Note', 3, 1051, 1, 15, 'new-issue-note.php', NULL, NULL),
(1060, 'New Return  Note', 3, 1052, 1, 15, 'new-return-note.php', NULL, NULL),
(1061, 'New Purchase Requisition - Store', 2, 8, 1, 1, 'new-pra.php', NULL, NULL),
(1062, 'Create GRN', 3, 6, 1, 1, 'create-grnc.php', NULL, NULL),
(1063, 'Issue Request List', 3, 1051, 1, 15, 'stock-issuance-list.php', NULL, NULL),
(1064, 'Issue Request Pending  List (Store)', 3, 1051, 1, 15, 'issue-pending-lists.php', NULL, NULL),
(1065, 'Issue Note List', 3, 1051, 1, 15, 'issue-note-list.php', NULL, NULL),
(1066, 'Return Request List', 3, 1052, 1, 15, 'return-requestion-list.php', NULL, NULL),
(1067, 'Return Note List', 3, 1052, 1, 15, 'return-note-list.php', NULL, NULL),
(1068, 'Purchase Requisition List', 3, 1024, 1, 13, 'manage-pr.php', NULL, NULL),
(1069, 'GRN List', 3, 1053, 1, 15, 'manage-grn.php', NULL, NULL),
(1100, 'New Production QC', 3, 2386, 1, 8, 'qc-criteria.php', NULL, NULL),
(1101, 'Manage Production QC', 3, 2386, 1, 8, 'manage-qc-criteria.php', NULL, NULL),
(1102, 'Production QC', 1, 1097, 1, 8, 'NULL', NULL, NULL),
(1103, 'Pending GRN (QC)', 2, 1097, 1, 8, 'manage-pending-grn-qc.php', NULL, NULL),
(1070, 'Return Request Pending  List (Department)', 3, 1052, 0, 15, 'return-pending-dept-lists.php', NULL, NULL),
(1071, 'Return Request Pending  List (Store)', 3, 1053, 0, 15, 'return-pending-lists.php', NULL, NULL),
(1099, 'Leads Status Box', 2, 1, 1, 7, 'NULL', NULL, NULL),
(1072, 'New Leads', 3, 1, 1, 7, 'new-lead.php', NULL, NULL),
(1073, 'Quotation Submitted', 3, 1, 1, 7, 'NULL', NULL, NULL),
(1074, 'Converted Sales', 3, 1, 1, 7, 'NULL', NULL, NULL),
(1075, 'Active Projects\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1076, 'Tasks Completed Today', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1077, 'Active Projects (PM)\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1078, 'Checklist Pending\r\n', 3, 1, 1, 9, 'project-pending-checklist.php', NULL, NULL),
(1079, 'LPR Pending\r\n', 3, 1, 1, 9, 'manage-pending-lpr.php', NULL, NULL),
(1080, 'Project Completed\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1081, 'Project Completed (PM)\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1082, 'EMPLOYEE PENDING CHECKLIST\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1083, 'PROJECT STATUS\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1084, 'CURRENT PROJECTS\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1085, 'CURRENT PROJECTS (PM)\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1086, 'CHECKLIST\r\n', 3, 1, 1, 9, 'project-checklist.php', NULL, NULL),
(1087, 'PROJECT CASTING\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1088, 'PROJECT PAYMENT\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1089, 'MONTH WISE SALE\r\n', 3, 1, 1, 9, 'report-month-wise-sales.php', NULL, NULL),
(1090, 'LPR STATUS\r\n', 3, 1, 1, 9, 'NULL', NULL, NULL),
(1091, 'Manage Pending MPS', 3, 211, 1, 8, 'NULL', NULL, NULL),
(1092, 'Manage Pending Job Order', 3, 212, 1, 8, 'rmr-pending-list.php', NULL, NULL),
(316, 'Pending Material Return list', 3, 293, 1, 8, 'manage-pending-mrrf.php', NULL, NULL),
(1094, 'Finish Goods Issuance Request', 3, 293, 1, 8, 'new-issue-request.php', NULL, NULL),
(1095, 'Pending Finish Goods Issuance list', 3, 293, 1, 8, 'manage-pending-mrrf2.php', NULL, NULL),
(1096, 'Finish Goods Issuance list', 3, 293, 1, 8, 'issue-note-list.php', NULL, NULL),
(1097, 'QC Department', 1, 0, 1, 8, 'NULL', NULL, NULL),
(1098, 'Pending Production QC', 2, 1102, 1, 8, 'pending-production-list.php', NULL, NULL),
(1105, 'Customer Project Milestones', 3, 0, 1, 1, 'NULL', NULL, NULL),
(1106, 'New Customer Project Milestones', 3, 0, 1, 1, 'NULL', NULL, NULL),
(1107, 'Manage Customer Project Milestones', 3, 0, 1, 1, 'customer-checklist.php', NULL, NULL),
(1108, 'Vendor Project Milestones', 3, 0, 1, 1, 'vendor-checklist.php', NULL, NULL),
(1109, 'New Vendor Project Milestones', 3, 0, 1, 1, 'NULL', NULL, NULL),
(1110, 'Manage Vendor Project Milestones', 3, 0, 1, 1, 'vendor-checklist.php', NULL, NULL),
(1111, 'Repair & Maintenance Report', 3, 0, 1, 8, 'NULL', NULL, NULL),
(1112, 'Employee Checklist', 3, 18, 1, 9, 'employee-checklist.php', NULL, NULL),
(1115, 'Import Bulk JV', 3, 16, 1, 1, 'NULL', NULL, NULL),
(1114, 'Finalize Production', 3, 213, 1, 8, 'NULL', NULL, NULL),
(1113, 'Quality & Maintenance Forms', 3, 0, 1, 1, '', NULL, NULL),
(1116, 'Top Products Monthly', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1117, 'Total Sales Monthly', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1154, 'New Form', 3, 1113, 1, 1, '', NULL, NULL),
(1118, 'Total Recovery Monthly', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1119, 'Total Receivable (All Time)', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1120, 'Total Payable (All Time)', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1121, 'Current Cash Position', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1122, 'Sales Journal (DYL Report)', 3, 620, 1, 1, 'NULL', NULL, NULL),
(1123, 'Purchase Journal (DYL Report)', 3, 626, 1, 1, 'NULL', NULL, NULL),
(1124, 'Bulk Product Creation', 1, 0, 0, 11, 'new-inventory-bulk.php', NULL, NULL),
(6045, 'Master POS Discount', 1, 0, 1, 11, 'master-pos-discount.php', NULL, NULL),
(1125, 'Day Closure (POS)', 1, 0, 1, 11, 'pos-day-close.php', NULL, NULL),
(1126, 'Machine Wise Production Report', 3, 1389, 1, 8, 'report-production-sheet2.php', NULL, NULL),
(1127, 'Production Capacity Analysys Report', 3, 1389, 1, 8, 'report-production-sheet13.php', NULL, NULL),
(1128, 'Machine  Wise Consumption Report', 3, 1389, 1, 8, 'report-production-sheet6.php', NULL, NULL),
(1129, 'Day Wise Production Report (Machine)', 3, 1389, 1, 8, 'report-production-sheet3.php', NULL, NULL),
(1130, 'Day Wise Production Report (Item)', 3, 1389, 1, 8, 'report-production-sheet12.php', NULL, NULL),
(1131, 'Day Wise Production Report (Worker)', 3, 1389, 1, 8, 'report-production-sheet4.php', NULL, NULL),
(1132, 'QC Analysis List Report', 3, 1389, 1, 8, 'report-production-sheet7.php', NULL, NULL),
(1133, 'Production Costing List Report', 3, 627, 1, 8, 'report-production-sheet14.php', NULL, NULL),
(1134, 'Production Costing Break Down Report', 3, 627, 1, 8, 'report-production-sheet15.php', NULL, NULL),
(1135, 'Production Costing Analysys Report', 3, 627, 1, 8, 'report-production-sheet16.php', NULL, NULL),
(1136, 'Break Down List Report', 3, 1389, 1, 8, 'report-production-sheet9.php', NULL, NULL),
(1137, 'Break Down Analysis Report', 3, 1389, 1, 8, 'report-production-sheet10.php', NULL, NULL),
(1138, 'Break Down Analysis Report (Machine Wise)', 3, 1389, 1, 8, 'report-production-sheet11.php', NULL, NULL),
(1139, 'PRODUCTION RATE (HOURLY)', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1140, 'PRODUCTION DAILY PROGRESS\r\n', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1141, 'PRODUCTION CAPACITY ANALYSIS\r\n', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1142, 'Production Output (Product)', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1143, 'Production Output (Machine Wise)', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1144, 'Production Output (Month Wise)', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1145, 'Lost Unit : Ratio', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1146, 'Lost Unit : Machine', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1147, 'Break Down Report', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1148, 'Break Down : Machine', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1149, 'Operational Cost (Month Wise)', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1150, 'Operations Cost breakdown', 2, 1, 1, 8, 'NULL', NULL, NULL),
(1151, 'Stock Aging Report', 3, 627, 1, 1, 'stock-aging-report.php', NULL, NULL),
(1152, 'Manage Form', 3, 1113, 1, 1, '', NULL, NULL),
(1153, 'Pending Submitted Forms', 3, 1113, 1, 1, '', NULL, NULL),
(1155, 'Action Forms (User Will Fill)', 3, 1113, 1, 1, '', NULL, NULL),
(1156, 'HR Request', 3, 0, 1, 9, 'NULL', NULL, NULL),
(1250, 'Gate Pass Status', 2, 1248, 1, 9, 'gatepass-request-status.php', NULL, NULL),
(1249, 'Request Gate Pass', 2, 1248, 1, 9, 'new-gatepass-request.php', NULL, NULL),
(1173, 'Goods Receiving Note (Pending)', 3, 291, 1, 1, 'manage-pending-approval-grn.php', NULL, NULL),
(1172, 'Goods Delivery Note (Pending)', 3, 289, 1, 1, 'manage-pending-approval-gdn.php', NULL, NULL),
(1158, 'Monthly Plan vs Call Progress Date wise Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1159, 'Monthly Plan vs Call Progress Doctor wise Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1160, 'Call Summary Report', 3, 0, 1, 3, 'call-summary-report.php', 'call-summary-report.php', NULL),
(1161, 'Product  Date Wise Call Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1162, 'Product  Doctor Wise Call Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1163, 'Monthly Plan Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1164, 'Product  Sampling Date wise Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1165, 'Product Sampling Doctor wise Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1166, 'Expense Summary Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1167, 'Adhoc Event Summary Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1168, 'Adhoc Event Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1169, 'Medical Rep. Attendance Sheet Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1170, 'Rep Progress Visual Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1171, 'Rep. Daily Activity Report', 3, 0, 1, 3, 'NULL', NULL, NULL),
(1174, 'Goods Receiving Note (SR) (Pending)', 3, 290, 1, 1, 'NULL', NULL, NULL),
(1175, 'Goods Delivery Note (PR) (Pending)', 3, 292, 1, 1, 'NULL', NULL, NULL),
(1176, 'Employee Loan / Advances Report', 3, 624, 1, 9, 'report-employee-loan.php', NULL, NULL),
(1177, 'Employee Loan / Advances Ledger Report', 3, 624, 1, 9, 'report-employee-loan2.php', NULL, NULL),
(1178, 'Rice Setup', 1, 0, 1, 16, 'NULL', NULL, NULL),
(1179, 'Inspection By', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1180, 'New Inspection By', 3, 1179, 1, 16, 'new-inspection.php', NULL, NULL),
(1181, 'Inspection By List', 3, 1179, 1, 16, 'manage-inspection.php', NULL, NULL),
(1182, 'Fumigation By', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1183, 'New Fumigation By', 3, 1182, 1, 16, 'new-fumigation.php', NULL, NULL),
(1184, 'Fumigation By List', 3, 1182, 1, 16, 'manage-fumigation.php', NULL, NULL),
(1185, 'Bag Type', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1186, 'New Bag Type', 3, 1185, 1, 16, 'new-bag-type.php', NULL, NULL),
(1187, 'Bag Type List', 3, 1185, 1, 16, 'manage-bag-type.php', NULL, NULL),
(1188, 'Production QC', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1189, 'New Production QC', 3, 1188, 1, 16, 'new-production-qc.php', NULL, NULL),
(1190, 'Production QC List', 3, 1188, 1, 16, 'Production QC List', NULL, NULL),
(1191, 'Bag Color', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1192, 'New Bag Color', 3, 1191, 1, 16, 'new-bag-color.php', NULL, NULL),
(1193, 'Manage Bag Color', 3, 1191, 1, 16, 'manage-bag-color.php', NULL, NULL),
(1194, 'Mill', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1195, 'New Mill', 3, 1194, 1, 16, 'new-mill.php', NULL, NULL),
(1196, 'Mill List', 3, 1194, 1, 16, 'new-mill.php', NULL, NULL),
(1197, 'Plant', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1198, 'New Plant', 3, 1197, 1, 16, 'new-plant.php', NULL, NULL),
(1199, 'Plant List', 3, 1197, 1, 16, 'manage-plant.php', NULL, NULL),
(1200, 'Galaa', 2, 1178, 1, 16, 'NULL', NULL, NULL),
(1201, 'New Galaa', 3, 1200, 1, 16, 'new-gala.php', NULL, NULL),
(1202, 'Galaa List', 3, 1200, 1, 16, 'manage-gala.php', NULL, NULL),
(1203, 'Print Setup', 2, 13, 1, 1, 'NULL', NULL, NULL),
(1204, 'New Sales Type', 3, 1203, 1, 1, 'new-sales-type.php', NULL, NULL),
(1205, 'Manage Sales Type', 3, 1203, 1, 1, 'sales-type-list.php', NULL, NULL),
(1206, 'Rice Discount', 3, 13, 1, 1, 'NULL', NULL, NULL),
(1207, 'New Rice Discount', 3, 1206, 1, 1, 'new-rice-discount.php', NULL, NULL),
(1208, 'Manage Rice Discount', 3, 1206, 1, 1, 'rice-discount-list.php', NULL, NULL),
(1237, 'Manage Pending Attendance', 3, 488, 1, 9, 'manage-pending-employee-attendance.php', NULL, NULL),
(1209, 'Print General Payment', 3, 15, 1, 1, 'print-gpvoucher.php', NULL, NULL),
(1210, 'Print General Receipt', 3, 15, 1, 1, 'print-grvoucher.php', NULL, NULL),
(1211, 'Print Sales Invoice', 3, 7, 1, 1, 'print-si.php', NULL, NULL),
(1212, 'Print Sales Order', 3, 7, 1, 1, 'print-so.php', NULL, NULL),
(1213, 'Print Purchase Order', 3, 8, 1, 1, 'print-po.php', NULL, NULL),
(1214, 'Print Goods Delivery Note', 3, 6, 1, 1, 'print-gdn.php', NULL, NULL),
(1215, 'Print Goods Receipt Note', 3, 6, 1, 1, 'print-grn.php', NULL, NULL),
(1216, 'Print Purchase Invoice', 3, 8, 1, 1, 'print-pi.php', NULL, NULL),
(1217, 'Print Sauda', 3, 0, 0, 0, 'print-sauda.php', NULL, NULL),
(1218, 'Print Quotation (Medi Teck)', 3, 7, 1, 1, 'print-quotation-mt.php', NULL, NULL),
(1219, 'Print Alteration Form', 3, 4, 1, 1, 'print-scredit-note.php', NULL, NULL),
(1220, 'Print Export Invoice', 3, 7, 1, 1, 'print-export-invoice.php', NULL, NULL),
(1221, 'Print Export Packing List', 3, 7, 1, 1, 'print-export-packing.php', NULL, NULL),
(1222, 'Print Export Sales Contract', 3, 7, 1, 1, 'print-export-contract.php', NULL, NULL),
(1223, 'Print Export Invoice Zaiqa', 3, 7, 1, 1, 'print-export-invoice-zaiqa', NULL, NULL),
(1224, 'Print Export Packing List Zaiqa', 3, 7, 1, 1, 'print-export-packing-zaiqa.php', NULL, NULL),
(1225, 'Print File System', 3, 1006, 1, 26, 'print-filesystem.php', NULL, NULL),
(1226, 'Print Opening Stock', 3, 2, 1, 1, 'print-opening-stock.php', NULL, NULL),
(1227, 'Customer Debit Note', 3, 4, 1, 1, 'print-scredit-note.php', NULL, NULL),
(1228, 'Customer Credit Note', 3, 4, 1, 1, 'print-sdebit-note.php', NULL, NULL),
(1229, 'Print Commercial Quotation (Details)', 3, 12, 1, 1, 'print-quotation3.php', NULL, NULL),
(1230, 'Print Quotation', 3, 12, 1, 1, 'print-quotation.php', NULL, NULL),
(1231, 'Print Quotation (Technical)', 3, 12, 1, 1, 'print-quotation2.php', NULL, NULL),
(1232, 'Print Stock In', 3, 6, 1, 1, 'print-stock-in.php', NULL, NULL),
(1233, 'Print Stock Out', 3, 6, 1, 1, 'print-stock-out.php', NULL, NULL),
(1234, 'Print SO (SND)', 3, 29, 1, 1, 'print-tso-so.php', NULL, NULL),
(1235, 'Print Barcode', 3, 2, 1, 1, 'print-barcode.php', NULL, NULL),
(1236, 'Print Barcode (Double)', 3, 2, 1, 1, 'print-barcode2.php', NULL, NULL),
(1238, 'Export Sale', 1, 0, 1, 1, 'NULL', NULL, NULL),
(1239, 'New Export Sale', 2, 1238, 1, 1, 'new-sales-export.php', NULL, NULL),
(1240, 'QC Report', 3, 626, 1, 1, 'report-qc.php', NULL, NULL),
(1241, 'Manage Export Sale', 2, 1238, 1, 1, 'manage-sales-export.php', NULL, NULL),
(1242, 'Warehouse Wise Arrival Report', 3, 626, 1, 1, 'report-warehouse-wise-arrival.php', NULL, NULL),
(1243, 'Local Sale / Dispatch Report', 3, 626, 1, 1, 'report-local-sale-dispatch.php', NULL, NULL),
(1247, 'Loans &amp; Advances  Issuance', 3, 494, 1, 9, 'loan-issuance.php', NULL, NULL),
(1248, 'Gate Pass', 2, 18, 1, 9, 'NULL', NULL, NULL),
(1251, 'Gate Pass Return', 2, 1248, 1, 9, 'gatepass-return.php', NULL, NULL),
(1252, 'Stores & Spares', 3, 0, 0, 15, '', NULL, NULL),
(1253, 'Pricing List', 3, 613, 0, 2, 'report-price-list.php', NULL, NULL),
(1254, 'Import Sauda Book', 3, 720, 1, 16, 'print-import-sauda-book.php', NULL, NULL),
(1255, 'Production Quality Wise Report', 3, 626, 0, 1, 'report-production-quality-wsie.php', NULL, NULL),
(1256, 'Sauda', 1, 0, 1, 16, 'NULL', NULL, NULL),
(1257, 'Record Sauda', 2, 1256, 1, 16, 'new-sauda.php', NULL, NULL),
(1258, 'Manage Sauda', 2, 1256, 1, 16, 'manage-sauda.php', NULL, NULL),
(1259, 'Delivery', 1, 0, 1, 1, 'NULL', NULL, NULL),
(1260, 'Goods Delivery Note (Sale)', 2, 1259, 1, 1, 'NULL', NULL, NULL),
(1261, 'Sauda Book', 1, 1820, 1, 16, 'report-sauda2.php', NULL, NULL),
(1262, 'Delivery Book', 1, 1820, 1, 16, 'report-sauda5.php', NULL, NULL),
(1263, 'Sauda Pending Report', 1, 1820, 1, 16, 'report-sauda4.php', NULL, NULL),
(1264, 'Party Account Book', 1, 1820, 1, 16, 'report-sauda3.php', NULL, NULL),
(1265, 'Customer Ledger', 1, 1820, 1, 16, 'dealer-ledger-detailed.php', NULL, NULL),
(1266, 'Customer Cash Book', 1, 1820, 1, 16, 'report-sauda7.php', NULL, NULL),
(1267, 'Cash Book', 1, 1820, 1, 16, 'cashbook-view2.php', NULL, NULL),
(1268, 'Stock Book', 1, 1820, 1, 16, 'report-sauda6.php', NULL, NULL),
(1269, 'Company Account Book', 1, 1820, 1, 16, 'report-sauda8.php', NULL, NULL),
(1270, 'Manage Delivery Terms', 2, 13, 1, 1, 'manage-delivery-terms.php', NULL, NULL),
(1271, 'Manage Payment Terms', 2, 13, 1, 1, 'manage-payment-terms.php', NULL, NULL),
(1272, 'Travel Expense Detail', 3, 613, 0, 3, 'report-travel-expense.php', NULL, NULL),
(1273, 'Travel Expense Report', 3, 613, 1, 3, 'travel-expense-report.php', NULL, NULL),
(1274, 'Investment Request Report', 3, 613, 1, 3, 'investment-request-report.php', NULL, NULL),
(1275, 'Investment Summary Report (Doctor Wise)', 3, 613, 1, 3, 'investment-summary-report.php', NULL, NULL),
(1276, 'investment-summary-report2.php', 3, 613, 1, 3, 'Investment Summary Report (Medical Rep Wise)', NULL, NULL),
(1277, 'Medical Rep Activity Summary Report', 3, 613, 1, 3, 'medical-rep-activity-report.php', NULL, NULL),
(1278, 'Medical Rep Visual Tracking Report', 3, 613, 1, 3, 'visual-tracking-report2.php', NULL, NULL),
(1284, 'Manage Pending Demo Plot', 2, 24, 1, 3, 'manage-pending-demo-plot.php', NULL, NULL),
(1280, 'Manage Pending Doctor Gifts', 2, 24, 1, 3, 'manage-pending-gift.php', NULL, NULL),
(1281, 'Manage Pending Travel Expense', 2, 24, 1, 3, 'manage-pending-travel-expense.php', NULL, NULL),
(1282, 'Manage Pending Investment Request', 2, 24, 1, 3, 'manage-pending-investment.php', NULL, NULL),
(1283, 'Manage Pending Call Report', 2, 24, 1, 3, 'manage-pending-call-report.php', NULL, NULL),
(1285, 'Manage Pending Daily Expense', 2, 24, 1, 3, 'manage-pending-daily-expense.php', NULL, NULL),
(1286, 'Manage Pending Adhoc Event', 2, 24, 1, 3, 'manage-pending-adhoc-event.php', NULL, NULL),
(1287, 'Manage Pending Monthly Promotion', 2, 24, 1, 3, 'manage-pending-monthly-promotion.php', NULL, NULL),
(1288, 'Daily Activity Report (POS)', 3, 620, 1, 11, 'report-daily-activity.php', NULL, NULL),
(1289, 'Salesman Wise Summary Report (POS)', 3, 620, 1, 11, 'report-salesman-wise-summary.php', NULL, NULL),
(1290, 'Pharmacy List Report', 3, 616, 1, 3, 'pharmacy-list-report.php', NULL, NULL),
(1291, 'Medical Rep. Attendance Sheet Report', 3, 615, 1, 3, 'tso-attendance-sheet.php', NULL, NULL),
(1292, 'Rep Progress Visual Report', 3, 615, 1, 3, 'load-sheet9.php', NULL, NULL),
(1293, 'Medical Rep Daily Activity Report', 3, 615, 1, 3, 'med-rep-daily-activity.php', NULL, NULL),
(1294, 'Medical Rep Daily Activity Report (Visual) ', 3, 615, 1, 3, 'med-rep-daily-activity2.php', NULL, NULL),
(1295, 'Medical Rep  Progress Report ', 3, 615, 1, 3, 'load-sheet4.php', NULL, NULL),
(1296, 'Visual Tracking Report', 3, 615, 1, 3, 'visual-tracking-report.php', NULL, NULL),
(1297, 'Check In Report', 3, 615, 1, 3, 'checkin-report.php', NULL, NULL),
-- (1298, 'Mileage Report', 3, 615, 1, 3, 'report-mileage.php', NULL, NULL),
(1300, 'Medical Rep. List', 3, 615, 1, 3, 'report-tso-list.php', NULL, NULL),
(1301, 'Daily Activity Report (POS)', 3, 620, 1, 11, 'report-daily-activity.php', NULL, NULL),
(1302, 'Salesman Wise Summary Report (POS)', 3, 620, 1, 11, 'report-salesman-wise-summary.php', NULL, NULL),
(1303, 'Import Product Stock', 3, 434, 1, 1, 'import-inventory-opening.php', NULL, NULL),
(1307, 'Print Sales Receipt Voucher', 3, 105, 1, 1, 'print-svoucher.php', NULL, NULL),
(1308, 'Print Purchase Payment Voucher', 3, 110, 1, 1, 'print-pvoucher.php', NULL, NULL),
(1309, 'Print Journal Voucher', 3, 119, 1, 1, 'print-generalentry.php', NULL, NULL),
(1310, 'Print General Payment Voucer', 3, 115, 1, 1, 'print-gpvoucher.php', NULL, NULL),
(1311, 'Print General Receipt Voucher', 3, 117, 1, 1, 'print-grvoucher.php', NULL, NULL),
(1312, 'Print Customer Credit Note', 3, 380, 1, 1, 'print-scredit-note.php', NULL, NULL),
(1313, 'Print Customer Debit Note', 3, 382, 1, 1, 'print-sdebit-note.php', NULL, NULL),
(1314, 'Print Vender Debit Note', 3, 351, 1, 1, 'print-pdebit-note.php', NULL, NULL),
(1315, 'Print Vender Credit Note', 3, 354, 1, 1, 'print-pcredit-note.php', NULL, NULL),
(1317, 'Approval Settings', 3, 557, 0, 3, 'approval-setting.php', NULL, NULL),
(1318, 'Manage Pending Work Plan', 2, 14, 0, 3, 'manage-pending-work-plan.php', NULL, NULL),
(1319, 'Manage Pending Doctor', 2, 14, 0, 3, 'manage-pending-doctor.php', NULL, NULL),
(1320, 'Visit Calls', 1, 0, 0, 3, '', NULL, NULL),
(1321, 'New Call', 1, 1320, 0, 3, '', NULL, NULL),
(1322, 'Manage Doctor Calls', 1, 1320, 0, 3, '', NULL, NULL),
(1323, 'Manage Pharmacy Calls', 1, 1320, 0, 3, '', NULL, NULL),
(1324, 'Manage Joint Calls', 1, 1320, 0, 3, '', NULL, NULL),
(1325, 'Work Plan', 1, 0, 0, 3, '', NULL, NULL),
(1326, 'New Work Plan', 1, 1325, 0, 3, '', NULL, NULL),
(1327, 'Pending Work Plan', 1, 1325, 0, 3, '', NULL, NULL),
(1328, 'Manage Work Plan', 1, 1325, 0, 3, '', NULL, NULL),
(1329, 'Import  Work Plan', 1, 1325, 0, 3, '', NULL, NULL),
(1330, 'Notification', 1, 0, 0, 3, '', NULL, NULL),
(1331, 'New Notification', 1, 1330, 0, 3, '', NULL, NULL),
(1332, 'Notification List', 1, 1330, 0, 3, '', NULL, NULL),
(1333, 'Support', 1, 0, 0, 3, '', NULL, NULL),
(1334, 'New Support Ticket', 1, 1333, 0, 3, '', NULL, NULL),
(1335, 'Manage Support', 1, 1333, 0, 3, '', NULL, NULL),
(1336, 'Doctor List Report', 3, 616, 1, 3, 'doctor-list-report.php', NULL, NULL),
(1337, 'Doctor Visual Report', 3, 616, 1, 3, 'load-sheet2.php', NULL, NULL),
(1339, 'Account Activity Report', 1, 0, 1, 16, 'filesystem-view.php', NULL, NULL),
(1340, 'Account Type Report', 1, 0, 1, 16, 'filesystem-view2.php', NULL, NULL),
(1341, ' Top 5 Customer (Receivables)', 2, 1, 0, 1, 'NULL', NULL, NULL),
(1342, 'Manage Travel Expense', 2, 1338, 1, 3, 'manage-travel-expense.php', NULL, NULL),
(1338, 'Manage Call Report', 1, 0, 1, 3, 'NULL', NULL, NULL),
(1344, 'Medical Rep. Other Report', 2, 17, 0, 3, '', NULL, NULL),
(1345, 'Medical Rep. Tracking Report', 2, 17, 0, 3, '', NULL, NULL),
(1346, 'Last Location Report  (Visual) ', 2, 1345, 0, 3, '', NULL, NULL),
(1343, 'Manage Call Report', 2, 1338, 1, 3, 'manage-call-report.php', NULL, NULL),
(1347, 'Manage Doctor Gift', 2, 1338, 1, 3, 'manage-gift.php', NULL, NULL),
(1348, 'Manage Investment Request', 2, 1338, 1, 3, 'manage-investment.php', NULL, NULL),
(1349, 'Manage Monthly Promotion', 2, 1338, 1, 3, 'manage-monthly-promotion.php', NULL, NULL),
(1350, 'Goods Consumption Note', 3, 286, 1, 1, 'gcn.php', NULL, NULL),
(1351, 'Manage Goods Consumption Note', 3, 286, 1, 1, 'gcn-list.php', NULL, NULL),
(1352, 'New Inward Pass', 2, 8, 1, 1, 'create-inward-qc.php', NULL, NULL),
(1353, 'Inward Pass List', 2, 8, 1, 1, 'manage-inward-qc.php', NULL, NULL),
(1354, 'Manage Pending Inward QC (Approval)', 2, 8, 1, 1, 'manage-pending-inward-qc.php', NULL, NULL) ";
    
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn) );
    
    
    $sql = "INSERT INTO `temp_system_pages` (`id`, `page_label`, `access_heirarchy`, `parent`, `enable`, `type`, `link`, `log_link`, `log_name`) VALUES
(1355, 'Inward QC List (Attach PO)', 2, 8, 1, 1, 'manage-iqc-po-attach.php', NULL, NULL),
(1356, 'Inward QC (View)', 3, 8, 1, 1, 'print-inward-qc.php', NULL, NULL),
(1357, 'Product Wise Target Report (SG)', 3, 609, 0, 2, 'load-sheet11.php', NULL, NULL),
(1358, 'Shop Wise Sales Report (SG)', 3, 609, 0, 2, 'load-sheet12.php', NULL, NULL),
(1360, 'Project Budget vs Expense Summary Report', 3, 1359, 1, 1, 'report-filesystem-budget-expense-summary.php', NULL, NULL),
(1359, 'File System', 2, 17, 1, 1, 'NULL', NULL, NULL),
(1361, 'Project Expense Activity Report', 3, 1359, 1, 1, 'report-filesystem-expense-activity.php', NULL, NULL),
(1362, 'Pending (Inward Pass)', 2, 8, 1, 1, 'manage-pending-po-ip.php', NULL, NULL),
(1363, 'Customer Wise Pricing Sheet', 3, 618, 1, 1, 'report-customer-wise-pricing-sheet.php', NULL, NULL),
(1364, 'Customer Cheque Clearing Report', 3, 618, 1, 1, 'report-ccheque-clearing.php', NULL, NULL),
(1365, 'Supplier Cheque Clearing Report', 3, 621, 1, 1, 'report-vcheque-clearing.php', NULL, NULL),
(1366, 'Total Qty (KG) Received Today', 2, 1, 1, 16, 'NULL', NULL, NULL),
(1367, 'Total Qty (KG) Received current month', 2, 1, 1, 16, 'NULL', NULL, NULL),
(1368, 'Total Qty (KG) Dispatched Today', 2, 1, 1, 16, 'NULL', NULL, NULL),
(1369, 'Total Qty (KG) Dispatched current month', 2, 1, 1, 16, 'NULL', NULL, NULL),
(1370, 'Pending Job Order', 3, 212, 0, 8, 'manage-pending-jo.php', NULL, NULL),
(1371, 'Pending Production List', 3, 212, 1, 8, 'manage-pending-production.php', NULL, NULL),
(1372, 'Leads Funnel', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1373, 'Main Admin Details', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1374, 'Notice Board (Hr)', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1375, 'Attendance Summary', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1376, 'Leave Balance', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1377, 'Expense Claims', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1378, 'Pending Projects', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1379, 'Quanity Consumption Report', 3, 627, 1, 1, 'report-qty-consumption.php', NULL, NULL),
(1380, 'Value Consumption Report', 3, 627, 1, 1, 'report-value-consumption.php', NULL, NULL),
(1381, 'Issuance List Report', 3, 627, 0, 1, 'brand-list.php', NULL, NULL),
(1382, 'Quanity Consumption Report', 3, 931, 1, 1, 'report-qty-assest-consumption.php', NULL, NULL),
(1383, 'Value Consumption Report', 3, 931, 1, 1, 'report-value-assest-consumption.php', NULL, NULL),
(1384, 'Department Stock Movement Report', 3, 931, 1, 1, 'report-issuance-assest-list.php', NULL, NULL),
(1385, 'Employee Checklist (Project Wise)', 3, 1359, 1, 1, 'employee-checklist-filesystem-wise.php', NULL, NULL),
(1386, 'Distributor Sale', 1, 0, 0, 2, 'NULL', NULL, NULL),
(1387, 'New Distributor Sales', 2, 1386, 0, 2, 'new-distributor-sale.php', NULL, NULL),
(1388, 'Manage Distributor Sales', 2, 1386, 0, 2, 'distributor-sale-list.php', NULL, NULL),
(1389, 'Production Report', 2, 17, 1, 8, 'NULL', NULL, NULL),
(1390, 'Job Order Status Report', 3, 1389, 1, 8, 'report-job-order-status.php', NULL, NULL),
(1391, 'Rice Production Report', 3, 1389, 1, 8, 'report-production.php', NULL, NULL),
(1392, 'Item Wise Production Report', 3, 1389, 1, 8, 'report-item-wise-costing.php', NULL, NULL),
(1393, 'Report QC Analysis', 3, 1389, 1, 8, 'report-qc-analysis.php', NULL, NULL),
(1394, 'Quotation Approval Pending', 2, 8, 1, 1, 'approval-pending-quotation.php', NULL, NULL),
(1395, 'PP Approval Pending', 2, 8, 1, 1, 'manage-pending-pp.php', NULL, NULL),
(1396, 'Purchase Proposal List', 2, 8, 1, 1, 'manage-pp.php', NULL, NULL),
(1397, 'Purchase Orders Details Report', 3, 626, 1, 1, 'report-po-details.php', NULL, NULL),
(1398, 'Unit Cost Summary', 3, 1389, 1, 8, 'unit-costing-summary.php', NULL, NULL),
(146, 'Pending PO', 2, 8, 1, 1, 'NULL', NULL, NULL),
(1455, 'Indent Form', 1, 0, 1, 22, '', NULL, NULL),
(1750, 'Edit Sales Order', 3, 141, 1, 1, 'edit-so.php', NULL, NULL),
(1751, 'Create Sale Invoice', 3, 141, 1, 1, 'create-gsi.php', NULL, NULL),
(1977, 'Raw Material', 1, 0, 1, 12, 'NULL', NULL, NULL),
(1999, 'Verify Sale Order', 3, 141, 1, 2, 'edit-tso-so2.php', NULL, NULL),
(3310, 'Customer Ledger ', 3, 2402, 1, 2, 'customer-ledger.php', NULL, NULL),
(1423, 'Import / Update Assets', 2, 2, 0, 15, 'import-asset-opening.php', NULL, NULL),
(2344, 'Employee Performance Sheet', 3, 624, 1, 9, 'employee-perfomance-sheet.php', NULL, NULL),
(2345, 'Card No', 2, 2, 1, 1, 'NULL', NULL, NULL),
(2346, 'New Card No', 3, 2345, 1, 1, 'new-dlish-cardno.php', NULL, NULL),
(2347, 'Manage Card No', 3, 2345, 1, 1, 'manage-dlish-cardno.php', NULL, NULL),
(2348, 'Quotation Additional Approval Pending', 2, 8, 1, 1, 'additional-approval-pending-quotation.php', NULL, NULL),
(2349, 'Manage Additional Creation Funds Issuance', 2, 7, 1, 1, 'manage-pending-additional-fund.php', NULL, NULL),
(2350, 'Pending Floor Issuance QC', 3, 1102, 0, 8, 'floor-issuance-qc-pending.php', NULL, NULL),
(2278, 'New Quotation', 3, 1024, 0, 19, 'new-quotation-form.php', NULL, NULL),
(2366, 'Medical Rep Monthly Attendance Report', 3, 615, 1, 3, 'report-monthly-attendance-static.php', NULL, NULL),
(1738, 'Pending Production QC', 2, 1102, 0, 8, 'pending-production-list2.php', NULL, NULL),
(1734, 'Pending Production Schedule', 2, 11, 0, 8, 'pending-production-schedule.php', NULL, NULL),
(1399, 'New Purchase Requisition Services', 2, 8, 1, 1, 'new-prs.php', NULL, NULL),
(1400, 'Edit Purchase Requisition ', 2, 8, 1, 1, 'edit-pr-right.php', NULL, NULL),
(1401, 'Edit Purchase Requisition Service', 2, 8, 1, 1, 'edit-prs-right.php', NULL, NULL),
(1402, 'Print Purchase Requisition', 3, 8, 1, 1, 'print-pr.php', NULL, NULL),
(1403, 'Pending RFQ(s)', 2, 8, 1, 1, 'manage-pending-tpr3.php', NULL, NULL),
(1404, 'Purchase Proposal Creation (Pending)', 2, 8, 1, 1, 'manage-pending-po2.php', NULL, NULL),
(1405, 'New Purchase Proposal', 2, 8, 1, 1, 'create-pp.php', NULL, NULL),
(1406, 'New Quotation', 2, 8, 1, 1, 'new-quotation2.php', NULL, NULL),
(1407, 'New Quotation Services', 2, 8, 1, 1, 'new-quotation3.php', NULL, NULL),
(1408, 'New Purchase Proposal Services', 2, 8, 1, 1, 'create-pps.php', NULL, NULL),
(1409, 'Edit Purchase Proposal Services', 2, 8, 1, 1, 'edit-pps.php', NULL, NULL),
(1410, 'Edit Purchase Proposal ', 2, 8, 1, 1, 'edit-pp.php', NULL, NULL),
(1411, 'Purchase Order Creation (Pending)', 2, 8, 1, 1, 'manage-pending-tpr4.php', NULL, NULL),
(1412, 'New Purchase (Service)', 2, 8, 1, 1, 'new-purchases.php', NULL, NULL),
(1413, 'Manage Work Order(s)', 2, 14, 1, 1, 'manage-work-order.php', NULL, NULL),
(1414, 'PR Status Report (Project Wise)', 3, 1359, 1, 1, 'report-pr-status-filesystem-wise.php', NULL, NULL),
(1415, 'Customer Checklist Report (Project Wise)', 3, 1359, 1, 1, 'report-customer-checklist-project-wise.php', NULL, NULL),
(1416, 'Vendor Checklist Report (Project Wise)', 3, 1359, 1, 1, 'report-vendor-checklist-project-wise.php', NULL, NULL),
(1417, 'Sauda Pending Report (Arrival/Dispatch)', 3, 627, 0, 1, 'report-rice-sauda-pending-delivery.php', NULL, NULL),
(1418, 'Stock Status Report', 3, 627, 0, 1, 'report-rice-stock-status-report.php', NULL, NULL),
(1419, 'Payment Collection Report', 3, 618, 1, 1, 'report-rice-payment-collection.php', NULL, NULL),
(1420, 'Brand Wise Stock Report (Summary)', 3, 627, 1, 1, 'report-rice-brand-wise-stock-summary.php', NULL, NULL),
(1421, 'Brand Wise Stock Report (Activity)', 3, 627, 1, 1, 'report-rice-brand-wise-stock-activity.php', NULL, NULL),
(1422, ' Chart of Accounts', 3, 16, 1, 1, 'report-chart-of-accounts.php', NULL, NULL),
(1424, 'Import Sauda Status Report', 3, 720, 1, 1, 'report-import-sauda-status.php', NULL, NULL),
(1425, 'Report Joint Call Confirmation', 3, 611, 0, 2, 'report-joint-call-confirmation.php', NULL, NULL),
(1426, 'Manage Pending Joint Call', 2, 14, 0, 3, 'manage-pending-jointcall.php', NULL, NULL),
(1427, 'Manage Joint Call', 1, 1338, 0, 3, 'manage-joint-call.php', NULL, NULL),
(1428, 'Hospital Survey List', 1, 1338, 0, 3, 'hospital-survey-list.php', NULL, NULL),
(1429, 'Manage Travel Expense', 1, 1338, 0, 3, 'manage-travel-expense2.php', NULL, NULL),
(1430, 'Manage Pending Travel Expense', 2, 14, 0, 3, 'manage-pending-travel-expense2.php', NULL, NULL),
(1431, 'Web Attachment', 1, 0, 0, 3, 'web-attachment.php', NULL, NULL),
(1432, 'SND Progress Dashboard', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1433, 'Weekly Checkin', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1434, 'Top 5 Product (Calls)', 2, 1, 0, 3, 'NULL', NULL, NULL),
(1435, 'Top 3 Products (Sales)', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1436, 'Yearly Progress Graph', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1437, 'Yearly Tracking Points Graph', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1438, 'Total Pharmacy', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1439, 'Total Medical Rep.', 2, 1, 0, 2, 'NULL', NULL, NULL),
(1440, 'Report Employee Payroll Sheet', 3, 624, 0, 9, 'report-employee-payroll-sheet.php', NULL, NULL),
(1441, 'TSO Target Report', 3, 610, 0, 2, 'salesman-wise-target2.php', NULL, NULL),
(1442, 'Product Wise Sales Target & Call Report ', 3, 610, 0, 2, 'report-product-wise-sales-target-callreport.php', NULL, NULL),
(1443, 'Update Internal Costing', 1, 0, 1, 1, 'manage-requirment-breif2.php', NULL, NULL),
(1444, 'Report Sample Request', 3, 614, 0, 3, 'report-sample-request.php', NULL, NULL),
(1445, 'Enquiry', 1, 0, 0, 22, '', NULL, NULL),
(1446, 'New Enquiry', 1, 1445, 0, 22, 'new-indent-enquiry.php', NULL, NULL),
(1447, 'Manage Enquiry', 1, 1445, 0, 22, 'manage-indent-enquiry.php', NULL, NULL),
(1448, 'Pending Enquiry', 1, 1445, 0, 22, 'pending-enquiry.php', NULL, NULL),
(1449, 'Pending Quotation Enquiry', 1, 1445, 0, 22, 'quotation-pending-enquiry.php', NULL, NULL),
(1450, 'Quotation', 1, 0, 0, 22, '', NULL, NULL),
(1451, 'New Quotation', 1, 1450, 0, 22, 'new-indent-quotation.php', NULL, NULL),
(1452, 'Manage Quotation', 1, 1450, 0, 22, 'manage-indent-quotation.php', NULL, NULL),
(1453, 'Pending Quotation', 1, 1450, 0, 22, 'pending-indent-quotation.php', NULL, NULL),
(1454, 'Pending indent Form Quotation', 1, 1450, 0, 22, 'indent-form-pending-quotation.php', NULL, NULL),
(1456, 'New Indent', 1, 1455, 0, 22, 'new-indent-form.php', NULL, NULL),
(1457, 'Manage Indent', 1, 1455, 0, 22, 'manage-indent-form.php', NULL, NULL),
(1458, 'Pending Indent LC', 1, 1455, 0, 22, 'pending-indent-form.php', NULL, NULL),
(1459, 'Indent LC', 1, 0, 0, 22, '', NULL, NULL),
(1460, 'New LC', 1, 1459, 0, 22, 'new-indent-lc.php', NULL, NULL),
(1461, 'Manage LC', 1, 1459, 0, 22, 'manage-indent-lc.php', NULL, NULL),
(1462, 'Pending LC Shipment', 1, 1459, 0, 22, 'pending-indent-lc.php', NULL, NULL),
(1463, 'Shipment', 1, 0, 0, 22, '', NULL, NULL),
(1464, 'New Shipment', 1, 1463, 0, 22, 'new-indent-shipment.php', NULL, NULL),
(1465, 'Manage Shipment', 1, 1463, 0, 22, 'manage-indent-shipment.php', NULL, NULL),
(1466, 'Commission', 1, 0, 0, 22, '', NULL, NULL),
(1467, 'New Commission', 1, 1466, 0, 22, 'new-indent-commission.php', NULL, NULL),
(1468, 'Sampling', 1, 0, 0, 22, '', NULL, NULL),
(1469, 'New Enquiry Form', 1, 1468, 0, 22, 'new-enquiry-form.php', NULL, NULL),
(1470, 'New Received Form', 1, 1468, 0, 22, 'new-received-form.php', NULL, NULL),
(1471, 'New Buyer Form', 1, 1468, 0, 22, 'new-buyer-form.php', NULL, NULL),
(1472, 'Manage All Finance Pending Vouchers', 2, 14, 1, 1, 'pending-finance-approval.php', NULL, NULL),
(1473, 'Manage Pending Customer Debit Note', 2, 14, 1, 1, 'manage-pending-cdn.php', NULL, NULL),
(1474, 'Manage Pending Customer Credit Note', 2, 14, 1, 1, 'manage-pending-ccn.php', NULL, NULL),
(1475, 'Manage Pending Supplier Debit Note', 2, 14, 1, 1, 'manage-pending-vdn.php', NULL, NULL),
(1476, 'Manage Pending Supplier Credit Note', 2, 14, 1, 1, 'manage-pending-vcn.php', NULL, NULL),
(1477, 'Manage Pending General Payment Voucher', 2, 14, 1, 1, 'manage-pending-gpv.php', NULL, NULL),
(1478, 'Manage Pending General Receipt Voucher', 2, 14, 1, 1, 'manage-pending-grv.php', NULL, NULL),
(1479, 'Manage Pending Receipt Voucher Sales', 2, 14, 1, 1, 'manage-pending-rvs.php', NULL, NULL),
(1480, 'Manage Pending Receipt Voucher Purchase', 2, 14, 1, 1, 'manage-pending-rvp.php', NULL, NULL),
(1481, 'Daily Production Approval List', 3, 213, 0, 8, 'manage-production-approval-list.php', NULL, NULL),
(1482, 'Sales Return List', 2, 7, 1, 1, 'manage-sr.php', NULL, NULL),
(1483, 'Leaves HR Approval', 3, 489, 0, 9, 'leave-request-status2.php', NULL, NULL),
(1484, 'Leaves List', 3, 489, 0, 9, 'manage-leave-request.php', NULL, NULL),
(1485, 'Leaves Immediate Manager Approval', 3, 489, 0, 9, 'leave-request-status3.php', NULL, NULL),
(1486, 'Half Day HR Approval', 3, 700, 1, 1, 'halfday-request-status2.php', NULL, NULL),
(1487, 'Immediate Manager Half Day Approval', 3, 700, 1, 1, 'halfday-request-status3.php', NULL, NULL),
(1488, 'Half Day List', 3, 700, 1, 1, 'manage-halfday-request.php', NULL, NULL),
(1489, 'Loans & Advances HR Approval', 3, 494, 0, 9, 'loan-request-status2.php', NULL, NULL),
(1490, 'Loans & Advances HR Approval', 3, 494, 0, 9, 'loan-request-status3.php', NULL, NULL),
(1491, 'Loans & Advances List', 3, 494, 0, 9, 'manage-loan-request.php', NULL, NULL),
(1492, 'Loans &amp; Advances Issuance List', 3, 494, 0, 9, 'loan-issuance-list.php', NULL, NULL),
(1493, 'Local Purchases', 3, 720, 1, 1, 'report-local-purchase.php', NULL, NULL),
(1494, 'Export Detail Report', 3, 720, 1, 1, 'report-rice-export-detail.php', NULL, NULL),
(1495, 'Export Summary Report', 3, 720, 1, 1, 'report-rice-export-summary.php', NULL, NULL),
(1496, 'Print Sales Tax Invoice', 3, 7, 1, 1, 'print-sti.php', NULL, NULL),
(1497, 'Print Sales Order ', 3, 194, 1, 1, 'print-sok.php', NULL, NULL),
(1498, 'Store Wise Testers Report', 3, 627, 1, 1, 'report-store-wise-testers.php', NULL, NULL),
(1500, 'Achievement Progress Report (Yearly)', 3, 609, 0, 2, 'report-achievement-progress.php', NULL, NULL),
(1501, 'Report Sample Request', 3, 609, 0, 2, 'report-sample-request.php', NULL, NULL),
(1502, 'SO Master Approval', 2, 14, 1, 1, 'manage-pending-tsom.php', NULL, NULL),
(1503, 'PO Master Approval', 2, 14, 1, 1, 'manage-pending-tpom.php', NULL, NULL),
(1504, 'Manage Commission', 1, 1466, 0, 22, 'manage-indent-commission.php', NULL, NULL),
(1505, 'Update Product', 2, 2, 1, 22, 'new-indent-item2.php', NULL, NULL),
(1506, 'Indent Setup', 2, 13, 1, 22, 'NULL', NULL, NULL),
(1507, 'Create City', 3, 1506, 1, 22, 'new-city.php', NULL, NULL),
(1508, 'Manage City', 3, 1506, 1, 22, 'manage-city.php', NULL, NULL),
(1509, 'Create Inco Terms', 3, 1506, 1, 22, 'new-incoterms.php', NULL, NULL),
(1510, 'Manage Inco Terms', 3, 1506, 1, 22, 'manage-incoterms.php', NULL, NULL),
(1511, 'Create Payment Mode', 3, 1506, 1, 22, 'new-payment-mode.php', NULL, NULL),
(1512, 'Manage Payment Mode', 3, 1506, 1, 22, 'manage-payment-mode.php', NULL, NULL),
(1513, 'Create Payment Terms', 3, 1506, 1, 22, 'new-payment-terms.php', NULL, NULL),
(1514, 'Manage Payment Terms', 3, 1506, 1, 22, 'manage-payment-terms2.php', NULL, NULL),
(1515, 'Create Shipment Mode', 3, 1506, 1, 22, 'new-shipment-mode.php', NULL, NULL),
(1516, 'Manage Shipment Mode', 3, 1506, 1, 22, 'manage-shipment-mode.php', NULL, NULL),
(1517, 'Create Standard Packing', 3, 1506, 1, 22, 'new-standard-packing.php', NULL, NULL),
(1518, 'Manage Standard Packing', 3, 1506, 1, 22, 'manage-standard-packing.php', NULL, NULL),
(1519, 'New Internal Production Order', 2, 7, 1, 1, 'new-internal-production-order.php', NULL, NULL),
(1520, 'Manage Internal Production Order Approval', 2, 14, 1, 1, 'manage-pending-ipo.php', NULL, NULL),
(1521, 'Manage Internal Production Order', 2, 7, 1, 1, 'manage-ipo.php', NULL, NULL),
(1522, 'Manage Creation Production Plan', 2, 7, 1, 1, 'manage-pending-cp-plan.php', NULL, NULL),
(1524, 'Sales Journal', 3, 620, 1, 1, 'report-sales-journalk.php', NULL, NULL),
(1527, 'Manage Creation Fund Request Against Production Plan', 2, 7, 1, 1, 'manage-pending-frap-plan.php', NULL, NULL),
(1525, 'Manage Production Plan', 2, 7, 1, 1, 'manage-pplan.php', NULL, NULL),
(1526, 'Manage Fund Request Against Production Plan Approval', 2, 14, 1, 1, 'manage-pending-frapp.php', NULL, NULL),
(1534, 'Department Stock Card Report', 3, 931, 0, 15, 'report-stock-assest-list.php', NULL, NULL),
(1535, 'Stock Depreciation Report', 3, 931, 0, 15, 'report-depreciation-assest-list.php', NULL, NULL),
(1530, 'Stock Issuance Pending Report', 3, 931, 0, 15, 'report-issuance-pending-list.php', NULL, NULL),
(1531, 'Stock Return pending Report', 3, 931, 0, 15, 'report-return-assest-list.php', NULL, NULL),
(1532, 'Perform Asset Depreciation', 3, 1640, 0, 15, 'asset-depreciation.php', NULL, NULL),
(1533, 'Asset Depreciation History', 3, 1640, 0, 15, 'asset-depreciation2.php', NULL, NULL),
(1640, 'Stock', 3, 0, 0, 15, '', NULL, NULL),
(1641, 'Stock Consumption', 3, 1640, 0, 15, 'asset-consumption2.php', NULL, NULL),
(1642, 'Consumption History', 3, 1640, 0, 15, 'asset-consumption.php', NULL, NULL),
(1536, 'General Reports', 2, 17, 0, 20, 'NULL', NULL, NULL),
(1537, 'Basic Transaction', 3, 1536, 0, 20, 'dsr-report-transaction44.php', NULL, NULL),
(1538, 'Pending Stockiest/ HO Transaction', 3, 1536, 0, 20, 'dsr-report-transaction67.php', NULL, NULL),
(1539, 'Data Uploading Report', 3, 1536, 0, 20, 'dsr-report-transaction50.php', NULL, NULL),
(1540, 'Product List', 3, 1536, 0, 20, 'dsr-report-transaction51.php', NULL, NULL),
(1541, 'Depot List', 3, 1536, 0, 20, 'dsr-report-transaction52.php', NULL, NULL),
(1542, 'Salesforce List', 3, 1536, 0, 20, 'dsr-report-transaction54.php', NULL, NULL),
(1543, 'Salesforce Target List', 3, 1536, 0, 20, 'dsr-report-transaction55.php', NULL, NULL),
(1544, 'Town List', 3, 1536, 0, 20, 'dsr-report-transaction53.php', NULL, NULL),
(1545, 'Town Salesforce Share', 3, 1536, 0, 20, 'dsr-report-transaction56.php', NULL, NULL),
(1546, 'Sales Reports', 2, 17, 0, 20, 'NULL', NULL, NULL),
(1547, 'Daily Sales Summary Report', 3, 1546, 0, 20, 'dsr-report-transaction65.php', NULL, NULL),
(1548, 'Product Wise Sales Report', 3, 1546, 0, 20, 'dsr-report-transaction64.php', NULL, NULL),
(1549, 'Product Wise Daily Sales Report', 3, 1546, 0, 20, 'dsr-report-transaction66.php', NULL, NULL),
(1550, 'Ranking Field Force Report', 3, 1546, 0, 20, 'dsr-report-transaction46.php', NULL, NULL),
(1551, 'Year Wise Product Sales Trend Report', 3, 1546, 0, 20, 'dsr-report-transaction48.php', NULL, NULL),
(1552, 'Sales Trend Report', 3, 1546, 0, 20, 'dsr-report-transaction57.php', NULL, NULL),
(1553, 'Product Range Wise Sales', 3, 1546, 0, 20, 'dsr-report-transaction47.php', NULL, NULL),
(1554, 'FF Targets vs Sales Report', 3, 1546, 0, 20, 'dsr-report-transaction49.php', NULL, NULL),
(1555, 'FF Top to Bottom Sales', 3, 1546, 0, 20, 'dsr-report-transaction60.php', NULL, NULL),
(1556, 'Zone Wise Sales Report', 3, 1546, 0, 20, 'dsr-report-transaction63.php', NULL, NULL),
(1557, 'National Sales Trend Report', 3, 1546, 0, 20, 'dsr-report-transaction61.php', NULL, NULL),
(1558, 'District Wise Targets v Sales Report', 3, 1546, 0, 20, 'dsr-report-transaction62.php', NULL, NULL),
(1559, 'New Product', 2, 1635, 0, 20, 'dsr-new-item.php', NULL, NULL),
(1560, 'Product List', 1635, 2, 0, 20, 'dsr-item-list.php', NULL, NULL),
(1567, 'Product Type', 2, 1635, 0, 20, 'NULL', NULL, NULL),
(1561, 'New Product Type', 3, 1567, 0, 20, 'dsr-new-item-type.php', NULL, NULL),
(1562, 'Manage Product Type', 3, 1567, 0, 20, 'dsr-manage-item-type.php', NULL, NULL),
(1568, 'Brands', 2, 1635, 0, 20, 'NULL', NULL, NULL),
(1563, 'New brand', 3, 1568, 0, 20, 'new-brand.php', NULL, NULL),
(1564, 'Brand List', 3, 1568, 0, 20, 'dsr-brand-list.php', NULL, NULL),
(1565, 'New Distributor', 2, 1636, 0, 20, 'dsr-new-distributor.php', NULL, NULL),
(1566, 'Distributor List', 2, 1636, 0, 20, 'dsr-distributor-list.php', NULL, NULL),
(1569, 'Distributor Products', 2, 1636, 0, 20, '', NULL, NULL),
(1570, 'Manage Distributor Products', 3, 1569, 0, 20, 'dsr-dproduct-list.php', NULL, NULL),
(1571, 'Pending Product (Mapping)', 3, 1569, 0, 20, 'dsr-dproduct-pending.php', NULL, NULL),
(1572, 'Distributor Areas', 2, 1636, 0, 20, '', NULL, NULL),
(1573, 'Manage Distributor Areas', 3, 1572, 0, 20, 'dsr-darea-list.php', NULL, NULL),
(1574, 'Pending Areas (Mapping)', 3, 1572, 0, 20, 'dsr-darea-pending.php', NULL, NULL),
(1575, 'Customer List', 1, 0, 0, 20, 'dsr-customer-list.php', NULL, NULL),
(1576, 'Data Management', 1, 0, 0, 20, '', NULL, NULL),
(1577, 'Upload Data', 2, 1576, 0, 20, 'dsr-import-data.php', NULL, NULL),
(1578, 'Upload Data (Other Formats)', 2, 1576, 0, 20, 'dsr-import-data-raypharma.php', NULL, NULL),
(1579, 'Products Mapping', 2, 1576, 0, 20, 'dsr-pending-data.php', NULL, NULL),
(1580, 'Pending Sales Mapping', 2, 1576, 0, 20, 'dsr-pending-sale.php', NULL, NULL),
(1581, 'Towns', 1, 0, 0, 20, '', NULL, NULL),
(1582, 'New Town', 2, 1581, 0, 20, 'dsr-new-pharmevo-area.php', NULL, NULL),
(1583, 'Manage Town', 2, 1581, 0, 20, 'dsr-manage-pharmevo-area.php', NULL, NULL),
(1584, 'Zones', 2, 1581, 0, 20, '', NULL, NULL),
(1585, 'New Zone', 3, 1584, 0, 20, 'dsr-new-dsr-zone.php', NULL, NULL),
(1586, 'Manage Zones', 3, 1584, 0, 20, 'dsr-zone-list.php', NULL, NULL),
(1587, 'Depot', 1, 0, 0, 20, '', NULL, NULL),
(1588, 'New Depot', 2, 1587, 0, 20, 'dsr-new-pharmevo-depot.php', NULL, NULL),
(1589, 'Manage Depot', 2, 1587, 0, 20, 'dsr-manage-pharmevo-depot.php', NULL, NULL),
(1590, 'Users', 1, 0, 0, 20, '', NULL, NULL),
(1591, 'New Employee', 2, 1590, 0, 20, 'dsr-new-employee.php', NULL, NULL),
(1592, 'Employee List', 2, 1590, 0, 20, 'dsr-employee-list.php', NULL, NULL),
(1593, 'Salesforce Target', 2, 1590, 0, 20, 'dsr-salesman-target.php', NULL, NULL),
(1594, 'Salesforce Area', 2, 1590, 0, 20, 'dsr-salesman-area.php', NULL, NULL),
(1595, 'Salesforce Area (Closed)', 2, 1590, 0, 20, 'dsr-salesman-area-closed.php', NULL, NULL),
(1596, 'Team', 2, 1590, 0, 20, '', NULL, NULL),
(1597, 'New Team', 3, 1596, 0, 20, 'dsr-new-department.php', NULL, NULL),
(1598, 'Manage Team', 3, 1596, 0, 20, 'dsr-user-department.php', NULL, NULL),
(1599, 'Designation', 2, 1590, 0, 20, '', NULL, NULL),
(1600, 'New Designation', 3, 1599, 0, 20, 'dsr-new-job-position.php', NULL, NULL),
(1601, 'Manage Designation', 3, 1599, 0, 20, 'dsr-user-position.php', NULL, NULL),
(1602, 'User Roles', 2, 1590, 0, 20, '', NULL, NULL),
(1603, 'New User Role', 3, 1602, 0, 20, 'dsr-new-user-role.php', NULL, NULL),
(1604, 'Manage User Role', 3, 1602, 0, 20, 'dsr-user-role.php', NULL, NULL),
(1605, 'Backup Data', 3, 553, 0, 20, 'dsr-export-data.php', NULL, NULL),
(1606, 'Restore Data', 3, 553, 0, 20, 'dsr-import-data.php', NULL, NULL),
(1607, 'Company Data', 2, 13, 0, 20, 'dsr-company-data.php', NULL, NULL),
(1608, 'Raw Data', 2, 13, 0, 20, 'dsr-data-display.php', NULL, NULL),
(1609, 'Basic Transaction Report', 2, 13, 0, 20, 'dsr-report-transaction.php', NULL, NULL),
(1610, 'Top 3 Zones', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1611, 'Top 3 Products', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1612, 'Top 3 Teams', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1613, 'Top 3 Brands', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1614, 'TOTAL STATS', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1615, 'Total Sales Today', 3, 1614, 0, 20, 'NULL', NULL, NULL),
(1616, 'Total Sales Current Month', 3, 1614, 0, 20, 'NULL', NULL, NULL),
(1617, 'Total Sales Previous month', 3, 1614, 0, 20, 'NULL', NULL, NULL),
(1618, 'Total Sales Force', 3, 1614, 0, 20, 'NULL', NULL, NULL),
(1619, 'Target Vs Sales Graph', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1620, 'TOTAL RB STATS', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1621, 'RB Sales Today', 3, 1620, 0, 20, 'NULL', NULL, NULL),
(1622, 'RB Sales Current Month', 3, 1620, 0, 20, 'NULL', NULL, NULL),
(1623, 'RB Sales Previous month', 3, 1620, 0, 20, 'NULL', NULL, NULL),
(1624, 'Total RB Products', 3, 1620, 0, 20, 'NULL', NULL, NULL),
(1625, 'TOTAL RPL STATS', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1626, 'RPL Sales Today', 3, 1625, 0, 20, 'NULL', NULL, NULL),
(1627, 'RPL Sales Current Month', 3, 1625, 0, 20, 'NULL', NULL, NULL),
(1628, 'RPL Sales Previous month', 3, 1625, 0, 20, 'NULL', NULL, NULL),
(1629, 'Total RPL Products', 3, 1625, 0, 20, 'NULL', NULL, NULL),
(1630, 'TOTAL OPTHA RPL STATS', 2, 1, 0, 20, 'NULL', NULL, NULL),
(1631, 'OPTHA RPL Sales Today', 3, 1630, 0, 20, 'NULL', NULL, NULL),
(1632, 'OPTHA RPL Sales Current Month', 3, 1630, 0, 20, 'NULL', NULL, NULL),
(1633, 'OPTHA RPL Sales Previous month', 3, 1630, 0, 20, 'NULL', NULL, NULL),
(1634, 'Total OPTHA RPL Products', 3, 1630, 0, 20, 'NULL', NULL, NULL),
(1635, 'Product', 1, 0, 0, 20, '', NULL, NULL),
(1636, 'Distributor', 1, 0, 0, 20, '', NULL, NULL),
(1637, 'New Quotation', 2, 8, 1, 1, 'new-quotation4.php', NULL, NULL),
(1638, 'Employee Loans & Advance Report', 3, 624, 0, 9, 'report-employee-loan-advance.php', NULL, NULL),
(1639, 'Pending PO Delivery Schedule', 2, 8, 1, 1, 'manage-pending-pod-scedule.php', NULL, NULL),
(1643, 'Transport Detail Report', 3, 620, 1, 1, 'report-transport-details.php', NULL, NULL),
(1644, 'Material Arrived', 2, 8, 1, 1, 'material-arrived-notification.php ', NULL, NULL),
(1645, 'Creation Job Order Pending', 3, 212, 0, 8, 'manage-pending-jod.php', NULL, NULL),
(1646, 'Manage Pending Material requisition list', 3, 293, 0, 8, 'pending-mrf-list.php', NULL, NULL),
(1648, 'Expense Statement Report', 2, 615, 0, 3, 'report-expense-statement.php', NULL, NULL),
(1657, 'Manage Stock Inward', 3, 1649, 1, 1, 'manage-material-in.php', NULL, NULL),
(1656, 'Stock Inward', 3, 1649, 1, 1, 'material-in.php', NULL, NULL),
(1650, 'Stock Outward', 3, 1649, 1, 1, 'material-out.php', NULL, NULL),
(1674, 'Sales Growth', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1675, 'Current Month | Previous Month', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1676, 'Sales Revenue by Sales Representative | Last 3 Month', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1677, 'Total Customers | YTD', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1678, 'Sales vs Target', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1679, 'Sales vs Target SKU Wise', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1680, 'Average Sales Medical Rep Wise', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1681, 'Avg Target value ', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1682, 'Medical Rep Date Wise Call Report', 3, 0, 0, 3, 'rep-datewise-report.php', NULL, NULL),
(1684, 'Expense vs Total Sales Value | Last Month', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1649, 'External material transfer', 2, 6, 1, 1, 'NULL', NULL, NULL),
(1685, 'Item Wise overall sales Chart | YTD', 2, 1, 0, 17, 'NULL', NULL, NULL),
(1647, 'Pending Material requisition Receiving list', 3, 293, 0, 8, 'manage-pending-mrr.php', NULL, NULL),
(1652, 'Create Currency', 3, 1506, 1, 22, 'new-currency.php', NULL, NULL),
(1653, 'Manage Currency', 3, 1506, 1, 22, 'manage-currency.php', NULL, NULL),
(1654, 'Create Dept Allied', 3, 1506, 1, 22, 'new-dept-allied.php', NULL, NULL),
(1655, 'Manage Dept Allied', 3, 1506, 1, 22, 'manage-dept-allied.php', NULL, NULL),
(1662, 'Product List', 2, 2, 1, 22, 'indent-item-list.php', NULL, NULL),
(1651, 'Manage Stock Outward', 3, 1649, 1, 1, 'manage-material-out.php', NULL, NULL),
(1658, 'Pending Purchase Service Invoice', 2, 8, 1, 1, 'manage-pending-gps.php', NULL, NULL),
(1659, 'Pending Internal Production Order', 2, 7, 1, 1, 'pending-internal-production-order.php', NULL, NULL),
(1660, 'New Booking Order', 2, 7, 1, 1, 'new-booking-order.php', NULL, NULL),
(1661, 'New Purchase Material Requisition', 2, 8, 1, 1, 'new-prc.php', NULL, NULL),
(1663, 'Production Bill', 2, 11, 1, 8, 'NULL', NULL, NULL),
(1664, 'New Production Bill', 3, 1663, 0, 8, 'new-production-bill.php', NULL, NULL),
(1665, 'Manage Production Bill', 3, 1663, 0, 8, 'manage-production-bill.php', NULL, NULL),
(1666, 'New Production Service', 3, 1663, 1, 8, 'new-production-service.php', NULL, NULL),
(1667, 'New Production Employee', 3, 1663, 0, 8, 'new-production-employee.php', NULL, NULL),
(1668, 'Employee Service Report', 3, 627, 1, 1, 'report-employee-service.php', NULL, NULL),
(1669, 'Booking Order Approval', 2, 14, 1, 1, 'manage-pending-tbo.php', NULL, NULL),
(1670, 'Booking Orders List', 2, 7, 1, 1, 'manage-bo.php', NULL, NULL),
(1671, 'Manage Funds Production Plan', 2, 7, 1, 1, 'manage-fapplan.php', NULL, NULL),
(1672, 'Manage Pending Funds Production Plan ', 2, 7, 1, 1, 'manage-pending-fapplan.php', NULL, NULL),
(1686, 'Costing', 1, 0, 0, 8, 'NULL', NULL, NULL),
(1687, 'New Costing Form', 2, 1686, 0, 8, 'new-costing-form-crescent.php', NULL, NULL),
(1688, 'Manage Costing', 2, 1686, 0, 8, 'manage-costing.php', NULL, NULL),
(1689, 'Unadjusted Vouchers (Purchase)', 3, 98, 1, 1, 'unadjusted-pvoucher.php', NULL, NULL),
(1690, 'Purchase Pending Payment Report', 3, 626, 1, 1, 'report-pending-payment.php', NULL, NULL),
(1691, 'New Sample Bom', 2, 1686, 0, 8, 'new-sample-bom-crescent.php', NULL, NULL),
(1694, 'Manage Discount Broken', 2, 1692, 1, 1, 'discount-broken-list.php', NULL, NULL),
(1693, 'New Discount Broken', 3, 1692, 1, 1, 'new-discount-broken.php', NULL, NULL),
(1692, 'Discount Broken', 2, 13, 1, 1, 'NULL', NULL, NULL),
(1695, 'Discount Moisture', 2, 13, 1, 1, 'NULL', NULL, NULL),
(1696, 'New Discount Moisture', 3, 1695, 1, 1, 'new-discount-moisture.php', NULL, NULL),
(1697, 'Manage Moisture Broken', 3, 1695, 1, 1, 'discount-moisture-list.php', NULL, NULL),
(1698, 'Pending Broker Invoice', 2, 8, 1, 1, 'manage-pending-gbo.php', NULL, NULL),
(1699, 'Pending Freight Invoice', 2, 8, 1, 1, 'manage-pending-gfo.php', NULL, NULL),
(1700, 'Broker Invoices', 2, 8, 1, 1, 'manage-purchaseb.php', NULL, NULL),
(1701, 'Freight Invoices', 2, 8, 1, 1, 'manage-purchasef.php', NULL, NULL),
(1707, 'Adjustments', 2, 18, 0, 9, '', NULL, NULL),
(1708, 'New Attendence Adjustment', 3, 1707, 0, 9, 'new-attendence-adjustment.php', NULL, NULL),
(1709, 'Manage Attendence Adjustment', 3, 1707, 0, 9, 'manage-attendence-adjustment.php', NULL, NULL),
(1710, 'New Amount Adjustment', 3, 1707, 0, 9, 'new-amount-adjustment.php', NULL, NULL),
(1711, 'Manage Amount Adjustment', 3, 1707, 0, 9, 'manage-amount-adjustment.php', NULL, NULL),
(1712, 'New Loan/Advance Adjustment', 3, 1707, 0, 9, 'new-loan-adjustment.php', NULL, NULL),
(1713, 'Manage Loan/Advance Adjustment', 3, 1707, 0, 9, 'manage-loan-adjustment.php', NULL, NULL),
(1705, 'Expired Contract GDN', 3, 289, 1, 1, 'manage-expired-gdn.php', NULL, NULL),
(1706, 'Expired Contract GRN', 3, 291, 1, 1, 'manage-expired-grn.php', NULL, NULL),
(1702, 'Delivery Book Report', 3, 626, 1, 1, 'report-buyer-seller.php', NULL, NULL),
(1703, 'Delivery Book Report', 3, 620, 1, 1, 'report-buyer-seller2.php', NULL, NULL),
(1704, 'Manage Sample Bom', 2, 1686, 0, 8, 'manage-sample-bom.php', NULL, NULL),
(1719, 'RFQ List', 2, 8, 1, 1, 'manage-rfq.php', NULL, NULL),
(1720, 'Quotations List', 2, 8, 1, 1, 'manage-quotation2.php', NULL, NULL),
(1714, 'Sauda Type', 3, 557, 1, 1, 'NULL', NULL, NULL),
(1715, 'New Sauda Type', 3, 1714, 1, 1, 'new-sauda-type.php', NULL, NULL),
(1716, 'Sauda Type List', 3, 1714, 1, 1, 'sauda-type-list.php', NULL, NULL),
(1717, 'Syah Advance Dashboard', 1, 0, 0, 17, 'dashboard.php', NULL, NULL),
(1718, 'Brokery Invoice Setup', 2, 13, 1, 1, 'brokery-setup.php', NULL, NULL),
(1721, 'General Ledger (Cumulative)', 3, 44, 1, 1, 'ledger-view2.php', NULL, NULL),
(1722, 'Product with No Purchase', 3, 620, 1, 1, 'report-customer-no-item.php', NULL, NULL),
(1723, 'Product list (Purchase Price Update)', 3, 627, 1, 1, 'report-item-price.php', NULL, NULL),
(1724, 'Product Purchase Price Updater', 2, 2, 1, 1, 'import-products5.php', NULL, NULL),

(1726, 'Daily Collection & Payment Summary\r\n', 3, 44, 1, 1, 'report-receipt-register3.php', NULL, NULL),
(1727, 'Trial Balance (Detailed #2)', 3, 44, 1, 1, 'trial-balance3.php', NULL, NULL),
(1728, 'Report Freight Payment', 3, 44, 1, 1, 'report-freight-payment.php', NULL, NULL),
(1729, 'Report Purchase Payment', 3, 44, 1, 1, 'report-purchase-payment.php', NULL, NULL),
(1730, 'Issuance Pending Finish Goods Issuance list', 3, 293, 1, 8, 'manage-pending-mrrf3.php', NULL, NULL),
(2002, 'Truck Status', 1, 0, 0, 19, 'truck-status.php', NULL, NULL),
(2003, 'Head Office (Pending)', 1, 0, 0, 19, 'ho-pending.php', NULL, NULL),
(2004, 'Gate', 1, 0, 0, 19, '', NULL, NULL),
(2005, 'New Truck Entry', 2, 2004, 0, 19, 'new-entry.php', NULL, NULL),
(2006, 'Full Rejection', 2, 2004, 0, 19, 'fullrejection.php', NULL, NULL),
(2007, 'User Registration  (Gate)', 1, 0, 0, 19, '', NULL, NULL),
(2008, 'New Broker', 2, 2007, 0, 19, 'new-vendor.php', NULL, NULL),
(2009, 'New Supplier', 2, 2007, 0, 19, 'new-supplier.php', NULL, NULL),
(2010, 'New Account Of', 2, 2007, 0, 19, 'new-account-of.php', NULL, NULL),
(2011, 'New Station', 2, 2007, 0, 19, 'new-station.php', NULL, NULL),
(2012, 'Quality Control', 1, 0, 0, 19, '', NULL, NULL),
(2013, 'First Sample', 2, 2012, 0, 19, 'qc-analysis.php', NULL, NULL),
(2014, 'Inner Sample', 2, 2012, 0, 19, 'inner-sample.php', NULL, NULL),
(2015, 'New Commodity', 2, 2012, 0, 19, 'new-item.php', NULL, NULL),
(2016, 'Hazoor Bukhsh &amp; Tabaar', 1, 0, 0, 19, 'tabaar.php', NULL, NULL),
(2017, 'Location Management', 1, 0, 0, 19, '', NULL, NULL),
(2018, 'Pending Location Management', 2, 2017, 0, 19, 'plocation-management.php', NULL, NULL),
(2019, 'Location Management', 2, 2017, 0, 19, 'location-management.php', NULL, NULL),
(2020, 'Weighbridge', 1, 0, 0, 19, 'weighbridge.php', NULL, NULL),
(2021, 'Field Worker', 1, 0, 0, 19, '', NULL, NULL),
(2022, 'Inner sample (Request)', 2, 2021, 0, 19, 'inner-sample-request.php', NULL, NULL),
(2023, 'Half Reject', 2, 2021, 0, 19, 'half-reject.php', NULL, NULL),
(2024, 'Confirm Unloading', 2, 2021, 0, 19, 'completion.php', NULL, NULL),
(2025, 'Accounts Area', 1, 0, 0, 19, '', NULL, NULL),
(2026, 'Pending Accounts', 2, 2025, 0, 19, 'pending-accounts.php', NULL, NULL),
(2027, 'Accounts', 2, 2025, 0, 19, 'accounts.php', NULL, NULL),
(2028, 'Pending Bilty', 1, 0, 0, 19, '', NULL, NULL),
(2029, 'Admin', 1, 0, 0, 19, 'admin.php', NULL, NULL),
(2030, 'Rice Setup', 1, 0, 0, 19, '', NULL, NULL),
(2031, 'Rice Settings', 1, 0, 0, 19, '', NULL, NULL),
(2033, 'Inventory Arrival Report', 2, 2032, 0, 19, '', NULL, NULL),
(1745, 'New Services Type', 2, 928, 1, 1, 'new-services-type.php', NULL, NULL),
(2035, 'Commodity Stock Position Report', 2, 2032, 0, 19, '', NULL, NULL),
(2037, 'Master File Report', 3, 2033, 0, 19, '', NULL, NULL),
(2038, 'Truck Detail Report', 3, 2033, 0, 19, '', NULL, NULL),
(2039, 'Truck Detail Report (Gate)', 3, 2033, 0, 19, '', NULL, NULL),
(2040, 'Truck Detail Report (Tabaar)', 3, 2033, 0, 19, '', NULL, NULL),
(2041, 'Truck Summary Report', 3, 2033, 0, 19, '', NULL, NULL),
(2042, 'Truck Timestamp Report', 3, 2033, 0, 19, '', NULL, NULL),
(2043, 'Product Arrival Report', 3, 2033, 0, 19, '', NULL, NULL),
(2044, 'Station Wise QC Analysis Report', 3, 2033, 0, 19, '', NULL, NULL),
(2045, 'QC Analysis Report', 3, 2033, 0, 19, 'report-qc-analys.php', NULL, NULL),
(2046, 'Filling Bags Report', 3, 2033, 0, 19, '', NULL, NULL),
(2047, 'Production Report', 3, 1389, 0, 19, 'report-production.php', NULL, NULL),
(2048, 'Production Summary Report', 3, 1389, 0, 19, '', NULL, NULL),
(2049, 'Raw Material Consumption Report', 3, 1389, 1, 19, '', NULL, NULL),
(2050, 'Raw Material Consumption Summary Report', 3, 1389, 1, 19, '', NULL, NULL),
(1740, 'New Inward QC', 2, 1739, 0, 8, 'new-inward-qc.php', NULL, NULL),
(1739, 'Inward QC', 1, 1097, 0, 8, 'NULL', NULL, NULL),
(1737, 'Import Outstanding Invoices Purchase (Old)', 3, 46, 1, 1, 'import-outstanding-purchase-invoices.php', NULL, NULL),
(1736, 'Production Schedule', 2, 11, 0, 8, 'NULL', NULL, NULL),
(1735, 'Manage Production Schedule', 2, 11, 0, 8, 'manage-production-schedule.php', NULL, NULL),
(1733, 'Net Sales Report', 3, 620, 1, 1, 'report-net-sales2.php', NULL, NULL),
(1732, 'Report Creditors Summary', 3, 44, 1, 1, 'report-creditors-summary.php', NULL, NULL),
(1731, 'Manage Material requisition Issuance list', 3, 293, 0, 8, 'manage-mmril.php', NULL, NULL),
(2072, 'Job Order', 1, 0, 0, 19, '', NULL, NULL),
(2073, 'New Job Order', 2, 2072, 0, 19, 'new-rice-job-order.php', NULL, NULL),
(2074, 'Manage Job Order', 2, 2072, 0, 19, 'rice-job-order-list.php', NULL, NULL),
(2075, 'New Bags Received', 2, 2072, 0, 19, 'new-bags-received.php', NULL, NULL),
(2076, 'Manage Bags Received', 2, 2072, 0, 19, 'manage-bags-received.php', NULL, NULL),
(2077, 'Daily Production', 1, 2000, 0, 19, 'daily-rice-production.php', NULL, NULL),
(2078, 'Production Sheet', 2, 2077, 0, 19, 'daily-rice-production.php', NULL, NULL),
(2079, 'Manage Production', 2, 2077, 0, 19, 'rice-production-list.php', NULL, NULL),
(2080, 'Head Office', 1, 0, 0, 19, '', NULL, NULL),
(2081, 'New Export Loading Program', 2, 2080, 0, 19, 'new-loading-req.php', NULL, NULL),
(2082, 'Container Export Loading Details', 2, 2080, 0, 19, 'new-loading-req-detail.php', NULL, NULL),
(2083, 'New Local Sales Program', 2, 2080, 0, 19, 'new-loading-req2.php', NULL, NULL),
(2084, 'Truck Local Loading Details', 2, 2080, 0, 19, 'new-loading-req-detail2.php', NULL, NULL),
(2085, 'Dispatch Location Management', 1, 0, 0, 19, 'new-loading-request.php', NULL, NULL),
(2086, 'Gate', 1, 0, 0, 19, 'loading-gate.php', NULL, NULL),
(2087, 'Weighbridge', 1, 0, 0, 19, 'loading-weighbridge.php', NULL, NULL),
(2088, 'QC Remarks', 1, 0, 0, 19, 'loading-qc-remarks.php', NULL, NULL),
(2089, 'Field Worker', 1, 0, 0, 19, 'loading-field-worker.php', NULL, NULL),
(2090, 'Account', 1, 0, 0, 19, 'loading-accounts.php', NULL, NULL),
(2091, 'Accounts (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2092, 'QC (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2093, 'Tabaar (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2094, 'Field Worker (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2095, 'Gate (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2096, 'Location (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2097, 'Weighbrage (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2098, 'Chart (Dashboard)   ', 3, 2001, 0, 19, '', NULL, NULL),
(2102, 'Tabaar (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2101, 'QC (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2100, 'Accounts (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2109, 'Truck Out (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2103, 'Field Worker (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2104, 'Gate (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2105, 'Location (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2106, 'Weighbrage (Outward)', 3, 2108, 0, 19, '', NULL, NULL),
(2107, 'Inward ', 2, 2001, 0, 19, '', NULL, NULL),
(2108, 'Outward', 2, 2001, 0, 19, '', NULL, NULL),
(2110, 'Head Office (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2111, 'Dashboard summary (Inward)', 3, 2107, 0, 19, '', NULL, NULL),
(2112, 'New Delivery Order', 2, 2080, 0, 19, 'new-delivery-order.php', NULL, NULL),
(2113, 'Manage Delivery Order', 2, 2080, 0, 19, 'delivery-order-list.php', NULL, NULL),
(2114, 'Manage Export Loading Program', 2, 2080, 0, 19, 'manage-export-program.php', NULL, NULL),
(2115, 'Manage Local Loading Program', 2, 2080, 0, 19, 'manage-local-program.php', NULL, NULL),
(2116, 'Custom  QC Form ', 1, 0, 0, 19, 'custom-qc-analysis.php', NULL, NULL),
(2117, 'New Custom  QC Form ', 3, 2117, 0, 19, '', NULL, NULL),
(2118, 'Manage Custom  QC Form ', 3, 2117, 0, 19, '', NULL, NULL),
(2128, 'Custom Qc sample report', 3, 2033, 0, 19, '', NULL, NULL),
(2120, 'Production QC', 1, 0, 0, 19, 'NULL', NULL, NULL),
(2121, 'Manage Production QC', 3, 2125, 0, 19, '', NULL, NULL),
(2123, 'Job Completion Report', 3, 1389, 0, 19, 'load-sheet-jcr.php', NULL, NULL),
(2124, 'Labour Bill Report', 3, 1389, 0, 19, '', NULL, NULL),
(2125, 'Energy Consumption Report', 3, 1389, 0, 19, '', NULL, NULL),
(2126, 'Mill Breakdown Report', 3, 1389, 0, 19, '', NULL, NULL),
(2127, 'Production QC Analysis Report', 3, 1389, 0, 19, '', NULL, NULL),
(2129, 'Weighbridge &amp; Sample Money Report', 3, 2033, 0, 19, '', NULL, NULL),
(2130, 'Head Office (Setup)', 1, 0, 0, 19, '', NULL, NULL),
(2131, 'New Quality Specification', 3, 2130, 0, 19, 'new-production-qc.php', NULL, NULL),
(2132, 'New Brand', 3, 2130, 0, 19, 'new-brand.php', NULL, NULL),
(2133, 'New Bag Type', 3, 2130, 0, 19, 'new-bag-type.php', NULL, NULL),
(2134, 'New Bag Colour', 3, 2130, 0, 19, 'NULL', NULL, NULL),
(2135, 'New Packing', 3, 2130, 0, 19, 'new-bag-packing.php', NULL, NULL),
(2291, 'Admin', 3, 142, 0, 19, 'admin-interwarehouse-transfer.php', NULL, NULL),
(2137, 'New Inspection By', 3, 2130, 0, 19, 'new-inspection.php', NULL, NULL),
(2138, 'New Fumigation By', 3, 2130, 0, 19, 'new-fumigation.php', NULL, NULL),
(2139, 'Inventory Dispatch Reports', 2, 2032, 0, 19, '', NULL, NULL),
(2140, 'Loading Detail Report (Export)', 3, 2139, 0, 19, 'report-loading-details.php', NULL, NULL),
(2141, 'Delivery Order Report (Export)', 3, 2139, 0, 19, 'report-delivery-order.php', NULL, NULL),
(2142, 'Warehouse Transfer', 1, 0, 0, 19, '', NULL, NULL),
(2143, 'New Warehouse Transfer', 3, 2142, 0, 19, 'transfer-stock2.php', NULL, NULL),
(2144, 'Field Worker Loading', 3, 2142, 0, 19, 'transfer-stock-loading-req.php', NULL, NULL),
(2145, 'Weighbridge', 3, 2142, 0, 19, 'weighbridge2.php', NULL, NULL),
(2146, 'Delivery Order', 3, 2142, 0, 19, 'new-transfer-do.php', NULL, NULL),
(2147, 'Accounts', 3, 2142, 0, 19, 'accounts2.php', NULL, NULL),
(2148, 'Manage Accounts', 3, 2142, 0, 19, 'manage-accounts.php', NULL, NULL),
(2149, 'Gate', 3, 2142, 0, 19, 'loading-gate2.php', NULL, NULL),
(2150, 'Field Worker UnLoading', 3, 2142, 0, 19, 'unloading-fieldworker.php', NULL, NULL),
(2151, 'Mill break Down', 2, 2077, 0, 19, 'mill-breakdown.php', NULL, NULL),
(2152, 'Electric Dept', 2, 2077, 0, 19, 'electric-dept.php', NULL, NULL),
(2153, 'Loading Accounts', 2, 2090, 0, 19, 'loading-accounts.php', NULL, NULL),
(2154, 'Manage Loading Accounts', 2, 2090, 0, 19, 'manage-loading-accounts.php', NULL, NULL),
(2155, 'Admin', 1, 0, 0, 19, '', NULL, NULL),
(2156, 'Dispatch Admin Local', 2, 2155, 0, 19, 'local-admin.php', NULL, NULL),
(2157, 'Dispatch Admin Export', 2, 2155, 0, 19, 'export-admin.php', NULL, NULL),
(2158, 'Warehouse Inter Transfer Reports', 2, 2032, 0, 19, '', NULL, NULL),
(2159, 'Inter Transfer Delivery Order Report', 3, 2158, 0, 19, 'report-transfer-delivery-order.php', NULL, NULL),
(2160, 'Inter Transfer Detail Report', 3, 2158, 0, 19, 'report-transfer-details.php', NULL, NULL),
(2165, 'Commodity Specification', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2166, 'New Commodity Specification', 3, 2165, 0, 19, 'new-item-type2.php', NULL, NULL),
(2167, 'Manage Commodity Specification', 3, 2165, 0, 19, 'manage-item-type2.php', NULL, NULL),
(2168, 'Broker', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2171, 'Field Worker', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2170, 'Broker List', 3, 2168, 0, 19, 'vendor-list.php', NULL, NULL),
(2173, 'Field List', 3, 2171, 0, 19, 'salesforce-list.php', NULL, NULL),
(2174, 'Production Item', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2175, 'New Production Item', 3, 2174, 0, 19, 'add-production-item.php', NULL, NULL),
(2176, 'Manage Production Item', 3, 2174, 0, 19, 'manage-production-item.php', NULL, NULL),
(2177, 'Party', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2178, 'New Party', 3, 2177, 0, 19, 'new-party.php', NULL, NULL),
(2179, 'Party List', 3, 2177, 0, 19, 'manage-party.php', NULL, NULL),
(2180, 'Dealer', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2183, 'Inspection By', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2182, 'Dealer List', 3, 2180, 0, 19, 'manage-supplier.php', NULL, NULL),
(2186, 'Fumigation By', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2185, 'Inspection By List', 3, 2183, 0, 19, 'manage-inspection.php', NULL, NULL),
(2187, 'Fumigation By List', 3, 2186, 0, 19, 'manage-fumigation.php', NULL, NULL),
(2188, 'Account of', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2189, 'Account of List', 3, 2188, 0, 19, 'manage-account-of.php', NULL, NULL),
(2190, 'Station', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2191, 'Station List', 3, 2190, 0, 19, 'manage-station.php', NULL, NULL),
(2192, 'Truck Type', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2193, 'New Truck Type', 3, 2192, 0, 19, 'new-truck-type.php', NULL, NULL),
(2194, 'Truck Type List', 3, 2192, 0, 19, 'manage-truck-type.php', NULL, NULL),
(2195, 'Sauda Terms', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2196, 'New Sauda Terms', 3, 2195, 0, 19, 'new-sauda-terms.php', NULL, NULL),
(2197, 'Sauda Terms List', 3, 2195, 0, 19, 'manage-sauda-terms.php', NULL, NULL),
(2198, 'Warehouse', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2199, 'New Warehouse', 3, 2198, 0, 19, 'new-warehouse.php', NULL, NULL),
(2200, 'Warehouse List', 3, 2198, 0, 19, 'manage-warehouse.php', NULL, NULL),
(2201, 'Mill', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2202, 'New Mill', 3, 2201, 0, 19, 'new-mill.php', NULL, NULL),
(2203, 'Mill List', 3, 2201, 0, 19, 'manage-mill.php', NULL, NULL),
(2204, 'Plant', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2205, 'New Plant', 3, 2204, 0, 19, 'new-plant.php', NULL, NULL),
(2206, 'Plant List', 3, 2204, 0, 19, 'manage-plant.php', NULL, NULL),
(2207, 'Polish', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2208, 'New Polish', 3, 2207, 0, 19, 'new-polish.php', NULL, NULL),
(2209, 'Polish List', 3, 2207, 0, 19, 'manage-polish.php', NULL, NULL),
(2210, 'Brand', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2212, 'Brand List', 3, 2210, 0, 19, 'brand-list.php', NULL, NULL),
(2213, 'Gala', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2214, 'New Gala', 3, 2213, 0, 19, 'new-gala.php', NULL, NULL),
(2215, 'Gala List', 3, 2213, 0, 19, 'manage-gala.php', NULL, NULL),
(2216, 'Cooking Type', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2217, 'New Cooking Type', 3, 2216, 0, 19, 'new-cooking-type.php', NULL, NULL),
(2218, 'Cooking Type List', 3, 2216, 0, 19, 'manage-cooking-type.php', NULL, NULL),
(2219, 'Location Type', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2220, 'New Location Type', 3, 2219, 0, 19, 'new-location-type.php', NULL, NULL),
(2221, 'Location Type List', 3, 2219, 0, 19, 'manage-location-type.php', NULL, NULL),
(2222, 'Dyed Color', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2223, 'New Dyed Color', 3, 2222, 0, 19, 'new-dyed-color.php', NULL, NULL),
(2224, 'Dyed Color List', 3, 2222, 0, 19, 'manage-dyed-color.php', NULL, NULL),
(2225, 'Bag Type', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2226, 'New Bag Type', 3, 2225, 0, 19, 'new-bag-type.php', NULL, NULL),
(2227, 'Bag Type List', 3, 2225, 0, 19, 'manage-bag-type.php', NULL, NULL),
(2228, 'Bag Packing', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2229, 'New Bag Packing', 3, 2228, 0, 19, 'new-bag-packing.php', NULL, NULL),
(2230, 'Bag Packing List', 3, 2228, 0, 19, 'manage-bag-packing.php', NULL, NULL),
(2231, 'QC Criteria (Production)', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2232, 'New QC Criteria (Production)', 3, 2231, 0, 19, 'new-production-qc.php', NULL, NULL),
(2233, 'QC Criteria (Production) List', 3, 2231, 0, 19, 'manage-production-qc.php', NULL, NULL),
(2243, 'Inter Transfer Delivery Order Difference Report', 3, 2158, 0, 19, 'report-transfer-do-differnce.php', NULL, NULL),
(2244, 'Bags Inventory Reports', 2, 2032, 0, 19, 'NULL', NULL, NULL),
(2245, 'Bags Stock Activity Report', 3, 2158, 0, 19, 'report-stock-bags-activity.php', NULL, NULL),
(2247, 'Commodity Stock Summary Galaa Wise Report', 3, 627, 0, 19, 'report-stock-summary-galaa.php', NULL, NULL),
(2248, 'Manage Emails', 3, 2013, 0, 19, 'manage-emails.php', NULL, NULL),
(2249, 'Product Stock', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2250, 'New Product Stock', 3, 2249, 0, 19, 'add-product-opening.php', NULL, NULL),
(2251, 'Manage Product Stock', 3, 2249, 0, 19, '', NULL, NULL),
(2252, 'Manage Delivery Order', 3, 2142, 0, 19, 'manage-transfer-do.php', NULL, NULL),
(2253, 'Local Production', 2, 2077, 0, 19, 'local-production.php', NULL, NULL),
(2254, 'Local Production List', 2, 2077, 0, 19, 'local-production-list.php', NULL, NULL),
(2255, 'Manage Warehouse Transfer', 3, 2142, 0, 19, 'manage-warehouse-transfer.php', NULL, NULL),
(2256, 'Bag Color', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2257, 'New Bag Color', 3, 2222, 0, 19, 'new-bag-color.php', NULL, NULL),
(2258, 'Manage Bag Color', 3, 2222, 0, 19, 'manage-bag-color.php', NULL, NULL),
(2260, 'New Production QC', 2, 2120, 0, 19, 'production-qc-analysis.php', NULL, NULL),
(2261, 'Manage QC Reporting', 3, 2120, 0, 19, 'manage-production-qc-analysis.php', NULL, NULL),
(2262, 'Arrival Image', 1, 0, 0, 19, 'arrival-image.php', NULL, NULL),
(2263, 'Labour Charge', 1, 0, 0, 19, '', NULL, NULL),
(2264, 'New Labour Charge', 2, 2263, 0, 19, 'new-labour-charge.php', NULL, NULL),
(2265, 'Manage Labour Charge', 2, 2263, 0, 19, 'labour-charge-list.php', NULL, NULL),
(2266, 'New Local Sales Order', 2, 2080, 0, 19, 'new-sales-order.php', NULL, NULL),
(2267, 'Local Sales Order List', 2, 2080, 0, 19, 'sales-order-list.php', NULL, NULL),
(2268, 'Local Sales Order Approval List', 2, 2080, 0, 19, 'pending-sales-order.php', NULL, NULL),
(2269, 'Logistics', 1, 2000, 0, 19, '', NULL, NULL),
(2270, 'Manage Logistics', 2, 2269, 0, 19, 'new-loading-req-detail3.php', NULL, NULL),
(2271, 'Head Office Logistics Approval', 2, 2269, 0, 19, 'logistics-approval.php', NULL, NULL),
(2272, 'Manage Logistics Trucks', 2, 2269, 0, 19, 'new-loading-req-detail4.php', NULL, NULL),
(2274, 'Store Supplier', 2, 2030, 0, 19, 'NULL', NULL, NULL),
(2275, 'Store Supplier List', 3, 2274, 0, 19, 'manage-store-supplier.php', NULL, NULL),
(2276, 'New Store Supplier', 3, 2274, 0, 19, 'new-store-supplier.php', NULL, NULL),
(2279, 'Quotation Approval', 3, 1024, 0, 19, 'manage-quotation-approval.php', NULL, NULL),
(2280, 'Manage Pending QC', 2, 2077, 0, 19, 'manage-pending-qc.php', NULL, NULL),
(2281, 'Manage QC', 2, 2077, 0, 19, 'manage-qc.php', NULL, NULL),
(2282, 'Manage QC Details', 2, 2077, 0, 19, 'manage-qc-details.php', NULL, NULL),
(2283, 'Manual Production', 1, 0, 0, 19, '', NULL, NULL),
(2284, 'Manual Production Sheet', 2, 2283, 0, 19, 'manual-production.php', NULL, NULL),
(2285, 'Manual Production List', 2, 2283, 0, 19, 'manual-production-list.php', NULL, NULL),
(2286, 'QC Criteria', 1, 0, 0, 19, 'NULL', NULL, NULL),
(2287, 'New QC Criteria', 2, 2286, 0, 19, 'new-qc-criteria.php', NULL, NULL),
(2288, 'Manage QC Criteria', 2, 2286, 0, 19, 'manage-qc-criteria.php', NULL, NULL),
(2290, 'PO VS Arrived Quantity Report', 3, 2036, 0, 19, 'report-store-status.php', NULL, NULL),
(2289, 'Manage QC Issues', 2, 2072, 0, 19, 'manage-issue-details.php', NULL, NULL),
(1741, 'Manage Inward QC', 2, 1739, 0, 8, 'manage-inward-qc2.php', NULL, NULL),
(1742, 'Manage Production QC', 3, 2386, 0, 8, 'production-qc-second.php', NULL, NULL),
(1743, 'Manage Production QC', 3, 2386, 0, 8, 'manage-production-qc-second.php', NULL, NULL),
(1746, 'Services Type List', 2, 928, 1, 1, 'manage-services-type.php', NULL, NULL),
(1747, 'New Production Criteria', 3, 1102, 0, 8, 'production-criteria.php', NULL, NULL),
(1748, 'Manage Production Criteria', 3, 1102, 0, 8, 'manage-production-criteria.php', NULL, NULL),
(1749, 'Edit Sales Invoice', 3, 141, 1, 1, 'edit-si.php', NULL, NULL),
(1752, 'Create GDN', 3, 141, 1, 1, 'create-gdn.php', NULL, NULL),
(1753, 'Verify Sale Order', 3, 141, 1, 1, 'edit-tso-so.php', NULL, NULL),
(1754, 'Receivable Turn Over Ratio Report', 3, 44, 1, 1, 'report-receivable-ratio.php', NULL, NULL) ";
    
    $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn) );
    
    
    

    
    $sql = "INSERT INTO `temp_system_pages` (`id`, `page_label`, `access_heirarchy`, `parent`, `enable`, `type`, `link`, `log_link`, `log_name`) VALUES
(1757, ' Daily Goods Received Report', 3, 627, 1, 1, 'report-arrival-status.php', NULL, NULL),
(1758, 'Customer Brand Wise Discount Sheet', 3, 620, 1, 1, 'report-customerbrand-wise-pricing-sheet.php', NULL, NULL),
(1759, 'Import Customer Brand Discount', 3, 6, 1, 1, 'import-customer-brand-discount.php', NULL, NULL),
(1760, 'TSO Wise Progress Report', 3, 620, 1, 1, 'load-sheet130.php', NULL, NULL),
(1761, 'Import SF Target File', 3, 557, 1, 1, 'import-appollo-target.php', NULL, NULL),
(1755, 'Daily Arrival Report', 3, 626, 1, 1, 'report-arrival.php', NULL, NULL),
(1756, 'Summary Of Post Date
    d Cheques', 1, 0, 0, 16, 'report-pdc-summary.php', NULL, NULL),
(1762, 'Indenting', 1, 0, 0, 22, 'NULL', NULL, NULL),
(1763, 'New Indenting Contract', 2, 1762, 0, 22, 'new-indenting-contract.php', NULL, NULL),
(1764, 'Pending Indenting Contracts', 2, 1762, 0, 22, 'pending-indenting-contracts.php', NULL, NULL),
(1765, 'Manage Indenting Contracts', 2, 1762, 0, 22, 'manage-indenting-contracts.php', NULL, NULL),
(1766, 'Manage Indenting Shipment', 2, 1762, 0, 22, 'manage-indenting-shipment.php', NULL, NULL),
(1767, 'Pending Indenting Credit Note', 2, 1762, 0, 22, 'pending-indenting-crnote.php', NULL, NULL),
(1768, 'Pending Indenting Debit Note', 2, 1762, 0, 22, 'pending-indenting-dnote.php', NULL, NULL),
(1769, 'BA Last Update Report', 2, 617, 0, 4, 'ba-datewise-report.php', NULL, NULL),
(1770, 'Customer Brand Tertiary Summary', 2, 617, 0, 4, 'customer-brand-tertiary-summary.php', NULL, NULL),
(1771, 'Pending Job Order Wise Material Requirement', 3, 1389, 0, 8, 'report-joborder-material.php', NULL, NULL),
(1772, 'Indenting Reports', 2, 0, 0, 22, 'NULL', NULL, NULL),
(1773, 'Sauda Book Report', 3, 1772, 0, 22, 'report-sauda-book.php', NULL, NULL),
(1774, 'Upcoming Consignment Update Summary', 3, 1772, 0, 22, 'report-saudabook-indent.php', NULL, NULL),
(1775, 'Profit &amp; Loss Statement', 3, 44, 0, 23, 'report-profit-report2.php', NULL, NULL),
(1776, 'Statement of Financial Position', 3, 44, 0, 23, 'balance-sheet2.php', NULL, NULL),
(1780, 'Booking (Builder)', 1, 0, 1, 21, 'NULL', NULL, NULL),
(1781, 'New Booking (Builder)', 1, 1780, 1, 21, 'new-reservation2.php', NULL, NULL),
(1782, 'Manage Booking (Builder)', 1, 1780, 1, 21, 'manage-reservation2.php', NULL, NULL),
(1783, 'Operations', 1, 0, 1, 21, 'NULL', NULL, NULL),
(1784, 'Pending Event Planning Meeting', 1, 1783, 0, 21, 'events-list.php', NULL, NULL),
(1785, 'Booking Received List', 1, 1783, 0, 21, 'new-booking-received.php', NULL, NULL),
(1786, 'Pending Booking Operations', 1, 1783, 0, 21, 'pending-booking-operations.php', NULL, NULL),
(1787, 'Pending Event Slots', 1, 1783, 0, 21, 'pending-event-slots.php', NULL, NULL),
(1788, 'Pending Event Planning', 1, 1783, 0, 21, 'pending-event-planning.php', NULL, NULL),
(1789, 'Event Planning Acknowledgment', 1, 1783, 0, 21, 'event-planning-acknowledgment.php', NULL, NULL),
(1790, 'Active Events', 1, 1783, 0, 21, 'active-events.php', NULL, NULL),
(1777, 'Discount Chalky', 2, 13, 0, 19, 'NULL', NULL, NULL),
(1778, 'New Discount Chalky', 3, 1777, 0, 19, 'new-discount-chalky.php', NULL, NULL),
(1779, 'Manage Discount Chalky', 3, 1777, 0, 19, 'discount-chalky-list.php', NULL, NULL),
(1791, 'Manage Closing', 1, 44, 0, 19, 'manage-closing.php', NULL, NULL),
(1792, 'New Rice Brokery Setup', 3, 1794, 0, 19, 'new-rice-brokery.php', NULL, NULL),
(1793, 'Manage Rice Brokery Setup', 3, 1794, 0, 19, 'rice-brokery-list.php', NULL, NULL),
(1794, 'Rice Brokery Setup', 2, 13, 0, 19, 'NULL', NULL, NULL),
(2292, 'Thadda Loading Details', 1, 0, 0, 19, 'new-gate-info.php', NULL, NULL),
(1795, 'Cheque Management', 1, 0, 1, 1, 'NULL', NULL, NULL),
(1796, 'New Cheque Entry', 2, 1795, 1, 1, 'new-cheque-entry.php', NULL, NULL),
(1797, 'Manage Cheque', 2, 1795, 1, 1, 'cheque-list.php', NULL, NULL),
(1800, 'New Event Shift', 3, 1795, 0, 1, 'new-event-shift.php', NULL, NULL),
(1801, 'Event Shift List', 3, 1795, 0, 1, 'manage-event-shift.php', NULL, NULL),
(1802, 'New Event Type', 3, 1795, 0, 1, 'new-event-type.php', NULL, NULL),
(1803, 'Event Type List', 3, 1795, 0, 1, 'manage-event-type.php', NULL, NULL),
(1804, 'New Lead Source', 3, 1795, 0, 1, 'new-lead-source.php', NULL, NULL),
(1805, 'Lead Source List', 3, 1795, 0, 1, 'manage-lead-source.php', NULL, NULL),
(8100, 'Employee  Final Settlement Form', 3, 1807, 0, 9, 'new-final-settlement.php', NULL, NULL),
(8101, 'Employee  Final Settlement List', 3, 1807, 0, 9, 'employee-list-final.php', NULL, NULL),
(8102, 'Employee Items', 3, 1156, 0, 9, '#', NULL, NULL),
(8103, 'Request Employee Items', 3, 8102, 0, 9, 'new-employeeitem-request.php', NULL, NULL),
(8104, 'Employee Items Status', 3, 8102, 0, 9, 'employeeitem-request-status.php', NULL, NULL),
(8105, 'Employee Items List', 3, 8102, 0, 9, 'employee-item-list.php', NULL, NULL),
(1806, 'Employee Items Return List', 3, 8102, 0, 9, 'employee-item-return.php', NULL, NULL),
(1807, 'Final Settlement', 2, 18, 0, 9, '#', NULL, NULL),
(1808, 'Pending Department Head Resignation Approval', 3, 1807, 0, 9, 'resignation-request-status.php', NULL, NULL),
(6486, 'Pending HR Resignation Approval', 3, 1807, 0, 9, 'resignation-request-status-hr.php', NULL, NULL),
(1809, 'Pending Final Settlement', 3, 1807, 0, 9, 'resignation-request-status2.php', NULL, NULL),
(1810, 'Pending Final Settlement Approval', 3, 1807, 0, 9, 'resignation-request-status3.php', NULL, NULL),
(1811, 'Gratuity Payable', 3, 101, 0, 9, 'gratuity-payable.php', NULL, NULL),
(1812, 'Manage Gratuity List', 3, 101, 0, 9, 'manage-gratuity-list.php', NULL, NULL),
(1813, 'Final Settlement  Payable', 3, 101, 0, 9, 'fsettlement-payable.php', NULL, NULL),
(1814, 'Manage Final Settlement List', 3, 101, 0, 9, 'manage-fsettlement-list.php', NULL, NULL),
(1815, 'Employee Gratuity', 2, 18, 0, 9, 'NULL', NULL, NULL),
(1816, 'Employee Gratuity  Request', 2, 1815, 0, 9, 'new-gratuity-request.php', NULL, NULL),
(1817, 'Employee Gratuity Immediate Manager Approval', 2, 1815, 0, 9, 'gratuity-request-status3.php', NULL, NULL),
(1818, 'Employee Gratuity HR Approval', 2, 1815, 0, 9, 'gratuity-request-status2.php', NULL, NULL),
(1819, 'Employee Gratuity  List', 2, 1815, 0, 9, 'manage-gratuity-request.php', NULL, NULL),
(1820, 'Rice Reports', 2, 17, 0, 16, '#', NULL, NULL),
(2299, 'New Custom QC', 2, 2077, 0, 19, 'new-custom-qc.php', NULL, NULL),
(2300, 'Manage Custom QC', 2, 2077, 0, 19, 'manage-custom-qc.php', NULL, NULL),
(2301, 'Hazoor Bukhsh & Tabaar Approval', 1, 0, 0, 19, 'tabaar-approval.php', NULL, NULL),
(1821, 'Cash Book', 1, 0, 1, 1, 'cashbook-view.php', NULL, NULL),
(1823, 'Loan Return Issuance', 2, 1492, 0, 9, 'loan-pending-return.php', NULL, NULL),
(1824, 'Loan Return List', 2, 494, 0, 9, 'loan-return-list.php', NULL, NULL),
(1825, 'Employee List (Probation)', 2, 484, 0, 9, 'employee-list-probation.php', NULL, NULL),
(1826, 'New Bulk Assessment Request', 2, 484, 0, 9, 'employee-bulk-assesment.php', NULL, NULL),
(1827, 'Pending Bulk Assessment Request', 2, 484, 0, 9, 'manage-pending-bulk-assesment.php', NULL, NULL),
(1828, 'Manage Bulk Assessment Request', 2, 484, 0, 9, 'manage-bulk-assesment.php', NULL, NULL),
(1829, 'Employee Bulk Advance Request', 2, 484, 0, 9, 'employee-bulk-advance.php', NULL, NULL),
(1830, 'Manage Pending Bulk Advance Request', 2, 484, 0, 9, 'manage-pending-bulk-advance.php', NULL, NULL),
(1831, 'Manage Bulk Advance Request', 2, 484, 0, 9, 'manage-employee-bulk-loans.php', NULL, NULL),
(1832, 'Employee Visit Attendance', 2, 484, 0, 9, '#', NULL, NULL),
(1833, 'Employee Visit Attendance  Request', 2, 484, 0, 9, 'new-visit-request.php', NULL, NULL),
(1834, 'Employee Visit Attendance Immediate Manager Approval', 2, 484, 0, 9, 'visit-request-status3.php', NULL, NULL),
(1835, 'Employee Visit Attendance HR Approval', 2, 484, 0, 9, 'visit-request-status2.php', NULL, NULL),
(1836, 'Employee Visit Attendance  List', 2, 484, 0, 9, 'manage-visit-request.php', NULL, NULL),
(1837, 'Events Calendar', 1, 1783, 0, 21, 'event-calendar.php', NULL, NULL),
(1838, 'Event Status', 1, 1783, 1, 21, '', NULL, NULL),
(1839, 'Event Banquet', 1, 1783, 1, 21, '', NULL, NULL),
(1840, 'Event Categories', 1, 1783, 1, 21, '', NULL, NULL),
(1841, 'Monthly Event Statistics', 1, 1783, 1, 21, '', NULL, NULL),
(1842, 'Performance Assessment Request HR Status ', 3, 492, 0, 9, 'appraisal-request-status2.php', NULL, NULL),
(1843, 'Manage  Performance Assessment', 3, 492, 0, 9, 'manage-appraisals.php', NULL, NULL),
(1844, 'Contract Update Sheet', 3, 1772, 0, 22, 'report-saudabook-indent2.php', NULL, NULL),
(1845, 'Food Packages', 2, 2, 0, 21, '#', NULL, NULL),
(1798, 'New Food Package', 2, 1845, 0, 21, 'new-deal-banquet.php', NULL, NULL),
(1799, 'Manage Food Package', 2, 1845, 0, 21, 'manage-deal-banquet.php', NULL, NULL),
(1850, 'Product Wise Sales Trend Report', 3, 620, 1, 1, 'load-sheet14.php', NULL, NULL),
(2308, 'Manage Pending Delivery Order', 3, 2142, 0, 19, 'manage-pending-transfer-do.php', NULL, NULL),
(2309, 'Pending Proforma Invoice', 2, 2302, 0, 19, 'pending-proforma-invoice.php', NULL, NULL),
(2310, 'Manage Proforma Invoice', 2, 2302, 0, 19, 'manage-proforma-invoice.php', NULL, NULL),
(1851, 'Employee Increment History Report', 3, 624, 0, 9, 'report-employee-increment-history.php', NULL, NULL),
(1852, 'Employee Paid by Cheque Report', 3, 624, 0, 9, 'report-employee-payroll-by-cheque.php', NULL, NULL),
(1853, 'Employee Paid by Cash Report', 3, 624, 0, 9, 'report-employee-payroll-by-cash.php', NULL, NULL),
(1854, 'Employee Paid by Bank Report', 3, 624, 0, 9, 'report-employee-payroll-by-bank.php', NULL, NULL),
(1855, 'Employee Payroll Summany  Report', 3, 624, 0, 9, 'report-employee-payroll-summary.php', NULL, NULL),
(1856, 'Employee Payroll Detail  Report', 3, 624, 0, 9, 'report-employee-payroll-detail.php', NULL, NULL),
(1857, 'Employee Tax Certificate Report', 3, 624, 0, 9, 'report-employee-payroll-slip.php', NULL, NULL),
(1858, 'Employee Pay Slip Report', 3, 624, 0, 9, 'report-employee-payroll-slip.php', NULL, NULL),
(1859, 'Employee Wise Item Issuance Report', 3, 8102, 0, 9, 'report-employee-item-list.php', NULL, NULL),
(1860, 'Employee Bulk Advance Request  Report', 3, 624, 0, 9, 'report-employee-bulk-advance.php', NULL, NULL),
(1861, ' Employee Document List   Report', 3, 624, 0, 9, 'report-employee-document.php', NULL, NULL),
(1870, 'Tax Certificate', 2, 18, 0, 9, '', NULL, NULL),
(1895, 'Employee Cheque Issuance (Pending)', 3, 101, 0, 9, 'salarycheque-payable.php', NULL, NULL),
(1871, 'Generate Tax Certificate', 3, 1870, 0, 9, 'new-tax-certificate.php', NULL, NULL),
(1872, 'Manage Tax Certificate', 3, 1870, 0, 9, 'manage-tax-certificate.php', NULL, NULL),
(1873, 'Print Tax Certificate', 3, 1872, 0, 9, 'print-tax-certificate.php', NULL, NULL),
(1896, 'Manage Employee Cheque Issuance List', 3, 101, 0, 9, 'manage-salarycheque-list.php', NULL, NULL),
(1897, 'Gratuity Calculation Statement ', 3, 624, 0, 9, 'report-employee-gratuity.php', NULL, NULL),
(1898, 'Gratuity Calculation Summary', 3, 624, 0, 9, 'report-employee-gratuity2.php', NULL, NULL),
(1899, 'Costing Reports', 2, 17, 1, 24, '#', NULL, NULL),
(1900, 'Sales Costing Sheet', 3, 1899, 1, 24, 'report-costing-sheet.php', NULL, NULL),
(1901, 'Unit Activity List', 3, 1899, 1, 24, 'dunit-costing-list.php', NULL, NULL),
(1902, 'Asset Activity List', 3, 1899, 1, 24, 'asset-costing-list.php', NULL, NULL),
(1903, 'Material Activity List', 3, 1899, 1, 24, 'rm-costing-list.php', NULL, NULL),
(1904, 'Inventory Valuation', 3, 1899, 1, 24, 'report-dwarehouse-inventory-valuation.php', NULL, NULL),
(1905, 'Material Stock Valuation', 3, 1899, 1, 24, 'report-warehouse-rm-valuation.php', NULL, NULL),
(2311, 'Pending Freight', 2, 2292, 0, 19, 'pending-bilty-freight.php', NULL, NULL),
(1906, 'Production Costing Sheet', 3, 1899, 1, 24, 'report-warehouse-rm-valuation.php', NULL, NULL),
(2312, 'Head Office (Pending)', 2, 2155, 0, 19, 'ho-spending.php', NULL, NULL),
(1822, 'Material requisition list (Issued)', 3, 293, 0, 8, 'manage-floor-issue.php', NULL, NULL),
(1846, 'Processing Program Stock Inward Report', 3, 628, 1, 1, 'report-processing-program-stockin.php', NULL, NULL),
(1847, 'Upload Invoice Image', 2, 7, 1, 1, 'crescent-invoice-image.php', NULL, NULL),
(1848, 'Processing Program Stock Outward Report', 3, 628, 1, 1, 'report-processing-program-stockout.php', NULL, NULL),
(1880, 'Pending Bilty Receiving', 2, 8, 1, 1, 'pending-bilty-receiving.php', NULL, NULL),
(1907, 'Manage Production Service', 3, 1663, 1, 8, 'manage-production-service.php', NULL, NULL),
(1908, 'Manage Production Employee', 3, 1663, 0, 8, 'manage-production-employee.php', NULL, NULL),
(1909, 'Weekly Wages Report', 3, 1389, 0, 8, 'report-weekly-wages.php', NULL, NULL),
(1849, 'Pending Freight Invoice', 2, 7, 1, 1, 'manage-pending-gfso.php', NULL, NULL),
(1865, 'Local Purchase Sauda', 2, 1256, 0, 19, 'NULL', NULL, NULL),
(1866, 'Record Local Purchase Sauda', 3, 1865, 0, 19, 'new-local-purchase-sauda.php', NULL, NULL),
(1867, 'Manage Local Purchase Sauda', 3, 1865, 0, 19, 'manage-local-purchase-sauda.php', NULL, NULL),
(1868, 'Import Sauda', 2, 1256, 0, 19, 'NULL', NULL, NULL),
(1869, 'Record Import Sauda', 3, 1868, 0, 19, 'new-import-sauda.php', NULL, NULL),
(1874, 'Manage Import Sauda', 3, 1868, 0, 19, 'manage-import-sauda.php', NULL, NULL),
(1875, 'Export Sauda', 2, 1256, 0, 19, 'NULL', NULL, NULL),
(1876, 'Record Export Sauda', 3, 1875, 0, 19, 'new-export-sauda.php', NULL, NULL),
(1877, 'Manage Export Sauda', 3, 1875, 0, 19, 'manage-export-sauda.php', NULL, NULL),
(1862, 'Local Sale Sauda', 2, 1256, 0, 19, 'NULL', NULL, NULL),
(1863, 'Record Local Sale Sauda', 3, 1862, 0, 19, 'new-local-sale-sauda.php', NULL, NULL),
(1864, 'Manage Local Sale Sauda', 3, 1832, 0, 19, 'manage-local-sale-sauda.php', NULL, NULL),
(1878, 'Warehouse Wise Arrival Report', 2, 1, 1, 1, 'NULL', NULL, NULL),
(1881, 'Available Stock', 2, 7, 1, 1, 'NULL', NULL, NULL),
(1882, 'New Available Stock', 3, 1881, 1, 1, 'new-custom-qta.php', NULL, NULL),
(1883, 'Pending Stock Available', 3, 1881, 1, 1, 'pending-custom-qta.php', NULL, NULL),
(1884, 'Available Stock List', 3, 1881, 1, 1, 'custom-qta-list.php', NULL, NULL),
(1910, 'Payments', 1, 0, 0, 21, 'NULL', NULL, NULL),
(1911, 'New Receipt Voucher', 1, 1910, 0, 21, 'new-booking-receipt.php', NULL, NULL),
(1912, 'Receipt Voucher List', 1, 1910, 0, 21, 'booking-receipt-list.php', NULL, NULL),
(1913, 'Booking Pending Payment List', 1, 1910, 0, 21, 'booking-pending-receipt-list.php', NULL, NULL),
(1914, 'Pre Event Meeting Calendar', 1, 0, 0, 21, 'event-calendar2.php', NULL, NULL),
(1915, 'Payment Pending Report', 2, 1921, 0, 21, 'events-pending-list.php', NULL, NULL),
(1916, 'Payment List Report', 2, 1921, 0, 21, 'events-payment-list.php', NULL, NULL),
(1917, 'Booking Pending Payment List (Due)', 1, 1910, 0, 21, 'booking-pending-receipt-list2.php', NULL, NULL),
(1918, 'Subscriber List Report', 2, 1921, 0, 21, 'events-subscriber-list.php', NULL, NULL),
(1673, 'Inventory Report', 3, 627, 1, 1, 'report-inventory-apparel.php', NULL, NULL),
(2034, 'Production Master Data', 3, 1389, 0, 19, 'report-production-master.php', NULL, NULL),
(1885, 'Store brand', 2, 2, 1, 1, 'NULL', NULL, NULL),
(1886, 'New Brand', 3, 1885, 1, 1, 'new-asset-brand.php', NULL, NULL),
(1887, 'Brand List', 3, 1885, 1, 1, 'asset-brand-list.php', NULL, NULL),
(1919, 'Report Debitors Summary', 3, 44, 1, 1, 'report-debitors-summary.php', NULL, NULL),
(1920, 'Event Rating Report', 2, 1921, 0, 21, 'events-rating-list.php', NULL, NULL),
(1921, 'Banquet Reports', 1, 0, 0, 21, '#', NULL, NULL),
(1922, 'Events List Report', 2, 1921, 0, 21, 'events-list2.php', NULL, NULL),
(1923, 'Events Planning Meeting List', 2, 1921, 0, 21, 'events-list3.php', NULL, NULL),
(1924, 'Customer Purchase Order', 2, 7, 0, 25, 'customer-manage-so.php', NULL, NULL),
(1925, 'Customer Payment Receipts', 2, 7, 0, 25, 'customer-sales-payment-receipts.php', NULL, NULL),
(1888, 'Store Planning', 2, 2, 1, 1, 'NULL', NULL, NULL),
(1889, 'New Planning', 3, 1888, 1, 1, 'new-store-planning-form.php', NULL, NULL),
(1890, 'Approval Planning', 3, 1888, 1, 1, 'planning-approval-list.php', NULL, NULL),
(1891, 'Planning List', 3, 1888, 1, 1, 'planning-list.php', NULL, NULL),
(1892, 'Approval Planning 2', 3, 1888, 1, 1, 'planning-approval-list2.php', NULL, NULL),
(1893, 'Issue Note Request vs Issue Note', 3, 2036, 1, 1, 'report-issue-request-details.php', NULL, NULL),
(1926, 'Receipt Voucher List', 1, 1910, 0, 21, 'booking-return-list.php', NULL, NULL),
(2246, 'Dispatch Bags Received', 2, 2072, 0, 19, 'dispatch-bags-received.php', NULL, NULL),
(1950, 'Customer PO vs SO Comparison Report', 3, 620, 0, 1, 'report-po-so.php', NULL, NULL),
(1927, 'Manage Pending Journal Voucher', 2, 14, 0, 1, 'manage-pending-general-journal.php', NULL, NULL),
(1951, 'BMS Payment List', 3, 620, 0, 1, 'bms-payment-list.php', NULL, NULL),
(3001, 'Task Creation', 2, 1028, 0, 1, 'project-checklist3.php', NULL, NULL),
(3002, 'Project Tasks (Pending)', 2, 1028, 0, 1, 'project-pending-checklist2.php', NULL, NULL),
(3003, 'Verify Task List', 2, 1028, 0, 1, 'project-approve-checklist.php', NULL, NULL),
(3750, 'Project Milestone Dashboard', 2, 1028, 0, 1, 'project-milestone-dashboard.php', NULL, NULL),
(3751, 'Project Milestone Import', 2, 1028, 0, 1, 'project-milestone-import.php', NULL, NULL),
(3752, 'Project Milestone Approval', 2, 1028, 0, 1, 'project-milestone-approval.php', NULL, NULL),
(3753, 'Project Milestone Change Approval', 2, 1028, 0, 1, 'project-milestone-change-approval.php', NULL, NULL),
(3754, 'Project Milestone Rejections', 2, 1028, 0, 1, 'project-milestone-rejected.php', NULL, NULL),
(3755, 'Project Milestone Visual Timeline', 2, 1028, 0, 1, 'project-milestone-visual.php', NULL, NULL),
(3756, 'Project Milestone Report', 2, 1028, 0, 1, 'project-milestone-report.php', NULL, NULL),
(3004, 'Store Stock Transfer', 1, 0, 1, 11, 'transfer-store-stock2.php', NULL, NULL),
(2351, 'Manage Pending Floor Inter Transfer', 3, 1102, 0, 8, 'manage-pending-floor-transfer.php', NULL, NULL),
(3005, 'Product Stock Audit', 2, 2, 1, 1, 'import-products7.php', NULL, NULL),
(3006, 'Store Closing Stock Report', 3, 627, 0, 11, 'report-warehouse-inventory-valuation7.php', NULL, NULL),
(3007, 'Manage Pending Travel Expense', 2, 14, 0, 3, 'manage-pending-travel-expense4.php', NULL, NULL),
(2352, 'Purchase Order Comparison Report', 3, 626, 1, 1, 'report-po-comparison.php', NULL, NULL),
(2353, 'Daily Purchase Report With Revised Rates Impact', 3, 626, 1, 1, 'report-daily-purchase.php', NULL, NULL),
(2354, 'Daily Local Sales Report', 3, 620, 1, 1, 'report-daily-sales.php', NULL, NULL),
(2355, 'Billed & Un Billed Arrivals Report', 3, 626, 1, 1, 'report-billed-unbilled.php', NULL, NULL),
(2356, 'Buyer Wise Sales Summary Report', 3, 620, 1, 1, 'report-buyer-wise-sales-summary.php', NULL, NULL),
(2357, 'Sales Invoice Movement Report With Receivable Position', 3, 620, 1, 1, 'report-sales-invoice-movment.php', NULL, NULL),
(2358, 'Manage Pending Stock Out', 3, 287, 1, 1, 'manage-pending-stock-out.php', NULL, NULL),
(2359, 'Manage Pending Stock Out Acknowledgement', 3, 287, 1, 1, 'manage-unacknowledged-stock-out.php', NULL, NULL),
(2360, 'Manage Pending Stock Outward', 3, 1649, 1, 1, 'manage-pending-material-out.php', NULL, NULL),
(2361, 'Manage Pending Stock Outward', 3, 1649, 1, 1, 'manage-pending-material-out.php', NULL, NULL),
(2362, 'Manage Pending Stock In', 3, 287, 1, 1, 'manage-pending-stock-in.php', NULL, NULL),
(2363, 'Manage Pending Stock In Acknowledgement', 3, 287, 1, 1, 'manage-unacknowledged-stock-in.php', NULL, NULL),
(2364, 'Manage Pending Stock Inward', 3, 1649, 1, 1, 'manage-pending-material-in.php', NULL, NULL),
(2365, 'Manage Pending Stock Inward Acknowledgement', 3, 1649, 1, 1, 'manage-unacknowledged-material-in.php', NULL, NULL),
(3008, 'Production Steps Stock Transfer (Issuance Pending)', 2, 13, 1, 1, 'workstation-pending-sample-list3.php', NULL, NULL),
(2367, 'General Journal', 3, 44, 1, 1, 'report-ledger-viewk.php', NULL, NULL),
(2368, 'MTD Progress', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2369, 'MTD Progress Category Wise', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2370, 'Total Receivable (360 Days) ', 2, 1, 1, 1, 'NULL', NULL, NULL),
(2371, 'Total Payable (360 Days)  ', 2, 1, 1, 1, 'NULL', NULL, NULL),
(2372, 'Stock Availability (FGS)', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2373, 'Stock Availability (Raw Material)', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2374, 'Cash Collection MTD', 2, 1, 1, 1, 'NULL', NULL, NULL),
(2375, 'Employee Check-in Checkout ', 2, 1, 1, 1, 'NULL', NULL, NULL),
(2376, 'WIP Total Cost', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2377, ' Production MTD Product', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2378, ' Production MTD Raw Material', 2, 1, 0, 1, 'NULL', NULL, NULL),
(2379, 'Debtors Aging Report', 3, 44, 1, 1, 'report-debtors-ageing.php', NULL, NULL),
(2380, 'Supplier Invoice Report', 3, 626, 1, 1, 'report-supplier-invoice.php', NULL, NULL),
(2381, 'Cash Flow', 3, 44, 1, 1, 'report-cashflow.php', NULL, NULL),
(3020, 'POS Daily Activity', 3, 1, 0, 11, '#', NULL, NULL),
(3021, 'POS Employee Attendance', 3, 1, 0, 11, '#', NULL, NULL),
(3300, 'Cash Movement', 1, 0, 0, 11, '#', NULL, NULL),
(3301, 'New Cash Movement', 2, 3300, 0, 11, 'cash-movement-entries.php', NULL, NULL),
(3302, 'Manage Cash Movement', 2, 3300, 0, 11, 'manage-cash-movement.php', NULL, NULL),
(1941, 'NULL', 3, 0, 1, 1, 'NULL', NULL, NULL),
(1956, 'Internal Store transfer', 2, 6, 1, 1, 'NULL', NULL, NULL),
(2402, 'Principle Reports', 2, 17, 1, 2, 'NULL', NULL, NULL),

(2404, 'Distributor Stock Summary Report', 3, 2402, 1, 1, 'Distributor Stock Summary Report', NULL, NULL),
(3303, 'Acknowledge For GRN', 1, 0, 1, 1, 'manage-pending-ak-tso.php', NULL, NULL),
(2395, 'Store Category', 2, 155, 1, 1, 'NULL', NULL, NULL),
(2383, 'Manage Pending Travel Expense', 2, 14, 0, 3, 'manage-pending-travel-expense4.php', NULL, NULL),
(2391, 'Export  Contract Detail', 2, 2030, 1, 19, 'NULL', NULL, NULL),
(2392, 'New Export Contract Detail', 2, 2391, 1, 19, 'new-export-contract-detail.php', NULL, NULL),
(2393, 'Export  Contract Detail List', 2, 2391, 1, 19, 'export-list-contract-detail.php', NULL, NULL),
(2382, 'Import POS Data', 2, 13, 1, 1, 'import-pos-data.php', NULL, NULL),
(2384, 'Payment Mode (POS)', 3, 557, 1, 1, 'NULL', NULL, NULL),
(2385, 'New Payment Mode', 3, 2384, 1, 1, 'new-pos-bank.php', NULL, NULL),
(2386, 'Payment Mode List', 3, 2384, 1, 1, 'manage-pos-bank.php', NULL, NULL),
(3009, 'Product Sample QC Result List', 2, 13, 1, 1, 'sample-qc-list.php', NULL, NULL),
(3010, 'Product Sample QC Result List (Pending)', 2, 13, 1, 1, 'sample-pending-qc-list.php', NULL, NULL),
(2387, 'Setup', 1, 1097, 1, 8, 'NULL', NULL, NULL),
(2388, 'New Production Criteria', 3, 2386, 0, 8, 'production-criteria.php', NULL, NULL),
(2389, 'Manage Production Criteria', 3, 2386, 0, 8, 'manage-production-criteria.php', NULL, NULL),
(2390, 'Bilty Details', 2, 57, 1, 1, 'bilty-detials.php', NULL, NULL),
(3022, 'PENDING SALES EXECUTION (POS)', 3, 1, 0, 11, 'manage-pending-pos-tso.php', NULL, NULL),
(3308, 'Branch Activity Report (POS)', 3, 620, 0, 11, 'report-daily-activity2.php', NULL, NULL),
(3304, 'Store Stock Transfer', 3, 620, 0, 11, 'transfer-store-stock2.php', NULL, NULL),
(3305, 'Product Stock Audit', 3, 0, 0, 11, 'import-products7.php', NULL, NULL),
(3307, 'Store Closing Stock Report', 3, 627, 0, 11, 'report-warehouse-inventory-valuation7.php', NULL, NULL),
(3100, 'Product   are below minimum stock level', 3, 0, 1, 1, 'min-inventory-report2.php', NULL, NULL),
(2396, 'New Assest Category', 3, 2395, 1, 1, 'new-asset-category.php', NULL, NULL),
(2397, 'Category List', 3, 2395, 1, 1, 'asset-category-list.php', NULL, NULL),
(2398, 'Location', 2, 2, 1, 1, 'NULL', NULL, NULL),
(2399, 'New Location', 3, 2398, 1, 1, 'new-asset-location.php', NULL, NULL),
(2400, 'Location List', 3, 2398, 1, 1, 'asset-location-list.php', NULL, NULL),
(2401, 'Salesman Wise Sales Report', 3, 610, 1, 2, 'report-tso-wise-sales.php', NULL, NULL),
(3311, 'Vendor Ledger', 3, 2402, 1, 2, 'vendor-ledger.php', NULL, NULL),
(1093, 'Manage Internal Costing', 3, 0, 1, 1, 'manage-import-internal-cost.php', NULL, NULL),
(3400, 'Manage Pending Payments', 3, 1780, 1, 21, 'manage-pending-payment.php', NULL, NULL),
(2458, 'WIP Total Cost', 2, 1, 0, 8, 'NULL', NULL, NULL),
(3405, 'No. of  Payments Due', 3, 1, 1, 21, '#', NULL, NULL),
(3406, 'Total Amount Due', 3, 1, 1, 21, '#', NULL, NULL),
(3407, 'Total Bookings', 3, 1, 1, 21, '#', NULL, NULL),
(3408, 'Amount Booked', 3, 1, 1, 21, '#', NULL, NULL),
(3409, 'Advance Received', 3, 1, 1, 21, '#', NULL, NULL),
(3410, 'Active Bookings', 3, 1, 1, 21, '#', NULL, NULL),
(3411, 'Payment Received (Today)', 3, 1, 1, 21, '#', NULL, NULL),
(3412, 'Payment Sent (Today)', 3, 1, 1, 21, '#', NULL, NULL),
(3413, 'Booking Milestone Pending Date', 3, 1780, 1, 21, 'booking-date-pending.php', NULL, NULL),
(1499, 'Monthly Expense Report', 3, 614, 1, 3, 'report-monthly-expense.php', NULL, NULL),
(1523, 'Sales Journal', 3, 620, 0, 1, 'report-sales-journalk.php', NULL, NULL),
(1528, 'Manage Creation Funds Issuance', 2, 7, 1, 1, 'pending-funds-issuance.php', NULL, NULL),
(1529, 'Manage Creation PR', 2, 7, 1, 1, 'manage-pending-pr-creation.php', NULL, NULL),
(1683, 'Manage Funds Issuance', 2, 7, 0, 1, 'manage-fund-issuance.php', NULL, NULL),
(1894, 'Manage Loading Port', 2, 13, 1, 1, 'manage-loading-port.php', NULL, NULL),
(1957, 'Transfer Stock', 3, 1956, 1, 15, 'transfer-stocka.php', NULL, NULL),
(1958, 'Transfer List', 3, 1956, 1, 15, 'warehouse-transfer-lista.php', NULL, NULL),
(1959, 'Stock in Transit', 3, 1956, 1, 15, 'warehouse-transfer-confirmation-lista.php', NULL, NULL),
(1960, 'Asset List Report', 3, 931, 1, 1, 'report-asset-list.php', NULL, NULL),
(2036, 'Store &amp; spare report', 2, 17, 1, 19, '', NULL, NULL),
(2051, 'Commodity Activity List Report', 3, 627, 1, 19, 'report-activity-list.php', NULL, NULL),
(2052, 'Commodity Stock Summary Report', 3, 627, 1, 19, 'report-stock-summary.php', NULL, NULL),
(2293, 'Local Truck Loading', 3, 2142, 1, 19, 'transfer-stock-loading-req2.php', NULL, NULL),
(2294, 'Qc Request (Pending)', 2, 2292, 1, 19, 'manage-pending-raise-request.php', NULL, NULL),
(2295, 'Raise Qc Request (Pending)', 2, 2292, 1, 19, 'manage-pending-po-qc.php', NULL, NULL),
(2296, 'Manage Qc Result (Pending)', 2, 2292, 1, 19, 'manage-pending-qc-result.php', NULL, NULL),
(2297, 'Tabbar Acknowledgement', 2, 2292, 1, 19, 'tabaar-acknowldge.php', NULL, NULL),
(2298, 'Thadda Loading Details', 2, 2292, 1, 19, 'new-gate-info.php', NULL, NULL),
(2302, 'Po Payment', 1, 0, 1, 19, 'NULL', NULL, NULL),
(2303, 'New Payment Request', 2, 2302, 1, 19, 'new-payment-request.php', NULL, NULL),
(2304, 'Pending Payment Request', 2, 2302, 1, 19, 'pending-payment-request.php', NULL, NULL),
(2305, 'Payment Request List', 2, 2302, 1, 19, 'manage-payment-request.php', NULL, NULL),
(2306, 'Issue Payment Request', 2, 2302, 1, 19, 'manage-pending-issue-request.php', NULL, NULL),
(2307, 'Freight (Pending)', 1, 0, 1, 19, 'freight-pending.php', NULL, NULL),
(2313, 'Arrival Accounts Area', 2, 2025, 1, 19, 'NULL', NULL, NULL),
(2314, 'Inter Warehouse Accounts Area', 2, 2025, 1, 19, 'NULL', NULL, NULL),
(2315, 'Weighbridges', 1, 0, 1, 19, 'NULL', NULL, NULL),
(2316, 'Inventory Dispatch Local Reports', 2, 17, 1, 19, 'NULL', NULL, NULL),
(2317, 'Loading Detail Report (Local)', 3, 2316, 1, 19, 'report-loading-details-local.php', NULL, NULL),
(2318, 'Delivery Order Report (Local)', 3, 2316, 1, 19, 'report-delivery-order-local.php', NULL, NULL),
(2319, 'Logistics Approval Inter Transfer', 3, 2142, 1, 19, 'transfer-logistics-approval.php', NULL, NULL),
(2320, 'Rejected Local Sales Order List', 2, 2080, 1, 19, 'rejected-sales-order-list.php', NULL, NULL),
(2321, 'Local / Export Program', 2, 2322, 1, 19, 'NULL', NULL, NULL),
(2322, 'Delivery Order', 1, 0, 0, 19, 'NULL', NULL, NULL),
(2323, 'Export Accruvals', 2, 2072, 1, 19, 'export-accruvals.php', NULL, NULL),
(2324, 'Thadda List', 2, 2292, 1, 19, 'manage-thadda-list.php', NULL, NULL),
(2325, 'Purchase Officer Freight Approval', 2, 2292, 1, 19, 'freight-approval-po.php', NULL, NULL),
(2326, 'Tabaar Freight Approval', 2, 2292, 1, 19, 'freight-approval-tabaar.php', NULL, NULL),
(2327, 'Report Monthly Expense', 3, 610, 1, 2, 'report-monthly-expense.php', NULL, NULL),
(2328, 'Return Note Request vs Return Note', 3, 2036, 1, 1, 'report-issue-return-request-details.php', NULL, NULL),
(2329, 'Manage Pending Travel Expense 2', 2, 14, 0, 3, 'manage-pending-travel-expense3.php', NULL, NULL),
(2330, 'Contract Balance Report', 3, 626, 1, 1, 'report-po-balance.php', NULL, NULL),
(2331, 'Purchase Officer Loading Approval', 2, 2292, 1, 19, 'gate-info-approval.php', NULL, NULL),
(2332, 'Tabaar Loading Approval', 2, 2292, 1, 19, 'gate-info-approval2.php', NULL, NULL),
(2333, 'Rice Sales List Report', 3, 620, 1, 1, 'report-rice-sales-list.php', NULL, NULL),
(2334, 'Thadda In Transit List', 2, 2292, 1, 19, 'manage-thadda-intransit-list.php', NULL, NULL),
(2335, 'Commodity Contribution KPI Report', 3, 620, 1, 1, 'report-commodity-contribution.php', NULL, NULL),
(2336, 'Summary Of Daily Sales Proceeds', 3, 620, 1, 1, 'report-summary-daily-sales-proceeds.php', NULL, NULL),
(2337, 'Daily Stock Outward Report', 3, 620, 1, 1, 'report-daily-stock-outward.php', NULL, NULL),
(2338, 'Pending DLTL', 2, 7, 1, 1, 'manage-pending-dltl.php', NULL, NULL),
(2339, 'Pending Rebate', 2, 7, 1, 1, 'manage-pending-rebate.php', NULL, NULL),
(2340, 'Sales Rebate Report', 3, 620, 1, 1, 'report-sales-rebate.php', NULL, NULL),
(2341, 'Sales DLTL Report', 3, 620, 1, 1, 'report-sales-dltl.php', NULL, NULL),
(2342, 'Product Import List', 3, 627, 1, 1, 'report-item-import-list.php', NULL, NULL),
(2343, 'PO Delivery Schedule List', 2, 8, 1, 1, 'manage-podsc.php', NULL, NULL),
(2452, 'Segment Wise Costing Sheet', 3, 1899, 1, 24, 'report-dwarehouse-inventory-valuation3.php', NULL, NULL),
(2453, 'Material Consumption Summary Report', 3, 1899, 1, 24, 'report-material-consumption-summary.php', NULL, NULL),
(2454, 'Material Summary Report', 3, 1899, 1, 24, 'report-material-summary.php', NULL, NULL),
(2455, 'Product Summary Report', 3, 1899, 1, 24, 'report-inventory-summary.php', NULL, NULL),
(2456, 'Product Summary Report 2', 3, 1899, 1, 24, 'report-fgs-inventory.php', NULL, NULL),
(2475, NULL, 3, 0, 1, 1, NULL, NULL, NULL),
(3402, 'User Quick Links Header', 3, 552, 1, 1, '#', NULL, NULL),
(3018, 'BOM creation (Pending)', 2, 3011, 1, 8, 'manage-pending-bom.php', NULL, NULL),
(3017, 'New BOM RND', 2, 3011, 1, 8, 'new-bom-rnd.php', NULL, NULL),
(3312, 'Sales Costing Report', 3, 1899, 0, 24, 'report-brand-wise-costing.php', NULL, NULL),
(3414, 'Update Shopify Sync Code', 3, 2, 0, 11, 'import-products8.php', NULL, NULL),
(3515, 'PR Quotation Attached', 2, 14, 0, 13, 'manage-pending-tpr6.php', NULL, NULL),
(3514, 'Sales Tax Product Wise Report', 2, 620, 1, 1, 'sales-tax-item-report.php', NULL, NULL),
(3513, 'Sales Tax Category Report', 2, 620, 1, 1, 'sales-tax-goods-report.php', NULL, NULL),
(2449, 'Manage Pending Unsynced Sales', 2, 7, 1, 1, 'manage-unsync-sales.php', NULL, NULL),
(3512, 'Month Wise Customer Sale Report', 2, 620, 1, 1, 'load-sheet15.php', NULL, NULL),
(3511, 'Project Management Dashboard', 2, 1, 0, 9, '', NULL, NULL),
(2700, 'QC Analysis Report (Tabaar)', 3, 2033, 0, 19, 'report-qc-analys-tabaar.php', NULL, NULL),
(2701, 'Mill break Down (Edit)', 3, 2077, 0, 19, 'edit-mill-breakdown.php', NULL, NULL),
(2702, 'Electric Dept (Edit)', 3, 2077, 0, 19, 'edit-electric-dept.php', NULL, NULL),
(3425, 'Bulk Barcode Printing', 3, 2, 0, 11, 'print-barcode-filter.php', NULL, NULL),
(3510, 'Labour Charges', 2, 287, 0, 2, 'md-labour-charges.php', NULL, NULL),
(3509, 'Stock In Summary Report', 2, 626, 0, 2, 'report-material-in.php', NULL, NULL),
(3508, 'Circle Transfer', 2, 1640, 0, 15, 'new-department-transfer.php', NULL, NULL),
(3507, 'Pending Return Request', 2, 1, 0, 15, '#', NULL, NULL),
(3506, 'Pending Issue Request', 2, 1, 0, 15, '#', NULL, NULL),
(3505, 'Stock Summary', 2, 1, 0, 15, '#', NULL, NULL),
(3504, 'Issue Request (In Process)', 2, 1, 0, 15, '#', NULL, NULL),
(3503, 'Item(s) Issued', 2, 1, 0, 15, '#', NULL, NULL),
(3502, 'Current Value', 2, 1, 0, 15, '#', NULL, NULL),
(3501, 'Depreciated Value', 2, 1, 0, 15, '#', NULL, NULL),
(3500, 'Total Assets Value', 2, 1, 0, 15, '#', NULL, NULL),
(3422, 'BOM Costing Report', 2, 1899, 0, 8, 'bom-costing-report.php', NULL, NULL),
(3011, 'RND', 2, 0, 1, 8, 'NULL', NULL, NULL),
(3012, 'Research & Development', 2, 3011, 1, 8, 'item-mapping-list-rnd.php', NULL, NULL),
(3013, 'New RND', 2, 3011, 1, 8, 'new-rnd.php', NULL, NULL),
(3014, 'Manage RND 1st Approval', 2, 3011, 1, 8, 'manage-pending-approval1.php', NULL, NULL),
(3015, 'Manage RND 2nd Approval', 2, 3011, 1, 8, 'manage-pending-approval2.php', NULL, NULL),
(3016, 'Approve RND', 2, 3011, 1, 8, 'approve-rnd.php', NULL, NULL),
(1945, 'Manage Stock Out', 3, 1941, 1, 15, 'manage-material-ina.php', NULL, NULL),
(1944, 'Stock Out Form', 3, 1941, 1, 15, 'material-ina.php', NULL, NULL),
(1943, 'Manage Stock In', 3, 1941, 1, 15, 'manage-material-outa.php', NULL, NULL),
(1942, 'Stock In Form', 3, 1941, 1, 15, 'material-outa.php', NULL, NULL),
(3421, 'Lead Follow Up List', 3, 1, 0, 9, '', NULL, NULL),
(3418, 'Dialing Screen', 3, 1, 0, 9, '', NULL, NULL),
(3419, 'Day Wise Lead Progress report', 3, 1, 0, 9, '', NULL, NULL),
(3420, 'Lead Progress Summary Report', 3, 1, 0, 9, '', NULL, NULL),
(3416, 'Attendance Management (Dashboard)', 3, 1, 0, 9, '', NULL, NULL),
(3417, 'Recurring Invoices', 3, 1, 0, 9, '', NULL, NULL),
(3415, 'Pending Recurring Invoices', 3, 1006, 0, 9, 'manage-recurring-so.php', NULL, NULL),
(2405, 'Manage Export Payment Terms', 1, 1178, 1, 16, 'manage-export-payment-term.php', NULL, NULL),
(2406, 'Inco Terms', 2, 2030, 1, 19, 'NULL', NULL, NULL),
(3023, 'Clock In / Clock Out', 3, 0, 0, 9, 'clock-in3.php', NULL, NULL),
(3309, 'Website Images', 2, 13, 0, 21, 'utilities-banquet.php', NULL, NULL),
(3401, 'User Quick Links', 3, 552, 1, 1, 'user-quick-links.php', NULL, NULL),
(2459, 'Production Semi Report', 3, 627, 1, 1, 'report-production-semi.php', NULL, NULL),
(3516, 'RAW MATERIAL STOCK AGING REPORT', 3, 628, 1, 1, 'stock-aging-reportc.php', NULL, NULL),
(4007, 'Sales Invoice Pending', 2, 4000, 0, 30, 'manage-pending-gsoj.php', NULL, NULL),
(3518, 'Sales Invoice Approval Pending', 2, 7, 0, 1, 'manage-pending-sales.php', NULL, NULL),
(4012, 'General Jounal (Approval 2)', 3, 0, 0, 1, NULL, NULL, NULL),
(4112, 'Asset Batch', '3', '0', '0', '10', NULL, NULL, NULL),
(2510, 'Distributor Wise Stock Level', '3', '0', '0', '2', 'min-distributor-inventory-report.php', NULL, NULL),
(3426, 'Pending Recurring Invoices', 3, 1006, 0, 9, 'manage-recurring-so.php', NULL, NULL),
(1279, '', 0, 0, 0, 0, '', '', '#'),
(1744, '', 0, 0, 0, 0, '', '', '#'),
(1879, '', 0, 0, 0, 0, '', '', '#'),
(1928, '', 0, 0, 0, 0, '', '', '#'),
(1929, '', 0, 0, 0, 0, '', '', '#'),
(1930, '', 0, 0, 0, 0, '', '', '#'),
(1931, '', 0, 0, 0, 0, '', '', '#'),
(1932, '', 0, 0, 0, 0, '', '', '#'),
(1933, '', 0, 0, 0, 0, '', '', '#'),
(1934, '', 0, 0, 0, 0, '', '', '#'),
(1935, '', 0, 0, 0, 0, '', '', '#'),
(1936, '', 0, 0, 0, 0, '', '', '#'),
(1937, '', 0, 0, 0, 0, '', '', '#'),
(1938, '', 0, 0, 0, 0, '', '', '#'),
(1939, '', 0, 0, 0, 0, '', '', '#'),
(1940, '', 0, 0, 0, 0, '', '', '#'),
(1946, '', 0, 0, 0, 0, '', '', '#'),
(1947, '', 0, 0, 0, 0, '', '', '#'),
(1948, '', 0, 0, 0, 0, '', '', '#'),
(1949, '', 0, 0, 0, 0, '', '', '#'),
(1952, '', 0, 0, 0, 0, '', '', '#'),
(1953, '', 0, 0, 0, 0, '', '', '#'),
(1954, '', 0, 0, 0, 0, '', '', '#'),
(1955, '', 0, 0, 0, 0, '', '', '#'),
(1961, '', 0, 0, 0, 0, '', '', '#'),
(1962, '', 0, 0, 0, 0, '', '', '#'),
(1963, '', 0, 0, 0, 0, '', '', '#'),
(1964, '', 0, 0, 0, 0, '', '', '#'),
(1965, '', 0, 0, 0, 0, '', '', '#'),
(1966, '', 0, 0, 0, 0, '', '', '#'),
(1967, '', 0, 0, 0, 0, '', '', '#'),
(1968, '', 0, 0, 0, 0, '', '', '#'),
(1969, '', 0, 0, 0, 0, '', '', '#'),
(1970, '', 0, 0, 0, 0, '', '', '#'),
(1971, '', 0, 0, 0, 0, '', '', '#'),
(1972, '', 0, 0, 0, 0, '', '', '#'),
(1973, '', 0, 0, 0, 0, '', '', '#'),
(1974, '', 0, 0, 0, 0, '', '', '#'),
(1975, '', 0, 0, 0, 0, '', '', '#'),
(1976, '', 0, 0, 0, 0, '', '', '#'),
(1978, '', 0, 0, 0, 0, '', '', '#'),
(1979, '', 0, 0, 0, 0, '', '', '#'),
(1980, '', 0, 0, 0, 0, '', '', '#'),
(1981, '', 0, 0, 0, 0, '', '', '#'),
(1982, '', 0, 0, 0, 0, '', '', '#'),
(1983, '', 0, 0, 0, 0, '', '', '#'),
(1984, '', 0, 0, 0, 0, '', '', '#'),
(1985, '', 0, 0, 0, 0, '', '', '#'),
(1986, '', 0, 0, 0, 0, '', '', '#'),
(1987, '', 0, 0, 0, 0, '', '', '#'),
(1988, '', 0, 0, 0, 0, '', '', '#'),
(1989, '', 0, 0, 0, 0, '', '', '#'),
(1990, '', 0, 0, 0, 0, '', '', '#'),
(1991, '', 0, 0, 0, 0, '', '', '#'),
(1992, '', 0, 0, 0, 0, '', '', '#'),
(1993, '', 0, 0, 0, 0, '', '', '#'),
(1994, '', 0, 0, 0, 0, '', '', '#'),
(1995, '', 0, 0, 0, 0, '', '', '#'),
(1996, '', 0, 0, 0, 0, '', '', '#'),
(1997, '', 0, 0, 0, 0, '', '', '#'),
(1998, '', 0, 0, 0, 0, '', '', '#'),
(2000, '', 0, 0, 0, 0, '', '', '#'),
(2424, '', 0, 0, 0, 0, '', '', '#'),
(2426, '', 0, 0, 0, 0, '', '', '#'),
(2436, '', 0, 0, 0, 0, '', '', '#'),
(2437, '', 0, 0, 0, 0, '', '', '#'),
(2438, '', 0, 0, 0, 0, '', '', '#'),
(2440, '', 0, 0, 0, 0, '', '', '#'),
(2441, '', 0, 0, 0, 0, '', '', '#'),
(2457, '', 0, 0, 0, 0, '', '', '#'),
(2461, '', 0, 0, 0, 0, '', '', '#'),
(2473, '', 0, 0, 0, 0, '', '', '#'),
(2476, '', 0, 0, 0, 0, '', '', '#'),
(2500, '', 0, 0, 0, 0, '', '', '#'),
(2501, '', 0, 0, 0, 0, '', '', '#'),
(2502, '', 0, 0, 0, 0, '', '', '#'),
(2503, '', 0, 0, 0, 0, '', '', '#'),
(2505, '', 0, 0, 0, 0, '', '', '#'),
(2555, '', 0, 0, 0, 0, '', '', '#'),
(2556, '', 0, 0, 0, 0, '', '', '#'),
(2557, '', 0, 0, 0, 0, '', '', '#'),
(2558, '', 0, 0, 0, 0, '', '', '#'),
(2559, '', 0, 0, 0, 0, '', '', '#'),
(2567, 'Distribution Pending PO', 0, 0, 0, 0, '', '', 'manage-pending-tpo-snd.php'),
(2581, '', 0, 0, 0, 0, '', '', '#'),
(2583, '', 0, 0, 0, 0, '', '', '#'),
(2591, '', 0, 0, 0, 0, '', '', '#'),
(2592, '', 0, 0, 0, 0, '', '', '#'),
(2604, '', 0, 0, 0, 0, '', '', '#'),
(3306, '', 0, 0, 0, 0, '', '', '#'),
(3450, '', 0, 0, 0, 0, '', '', '#'),
(3517, '', 0, 0, 0, 0, '', '', '#'),
(3520, '', 0, 0, 0, 0, '', '', '#'),
(3521, '', 0, 0, 0, 0, '', '', '#'),
(3522, '', 0, 0, 0, 0, '', '', '#'),
(3523, '', 0, 0, 0, 0, '', '', '#'),
(3524, '', 0, 0, 0, 0, '', '', '#'),
(3525, '', 0, 0, 0, 0, '', '', '#'),
(3528, '', 0, 0, 0, 0, '', '', '#'),
(3529, '', 0, 0, 0, 0, '', '', '#'),
(3532, '', 0, 0, 0, 0, '', '', '#'),
(3533, '', 0, 0, 0, 0, '', '', '#'),
(3534, '', 0, 0, 0, 0, '', '', '#'),
(3535, '', 0, 0, 0, 0, '', '', '#'),
(3536, '', 0, 0, 0, 0, '', '', '#'),
(3537, '', 0, 0, 0, 0, '', '', '#'),
(3538, '', 0, 0, 0, 0, '', '', '#'),
(3539, '', 0, 0, 0, 0, '', '', '#'),
(3540, '', 0, 0, 0, 0, '', '', '#'),
(3541, '', 0, 0, 0, 0, '', '', '#'),
(3542, '', 0, 0, 0, 0, '', '', '#'),
(3543, '', 0, 0, 0, 0, '', '', '#'),
(3544, '', 0, 0, 0, 0, '', '', '#'),
(3545, '', 0, 0, 0, 0, '', '', '#'),
(3546, '', 0, 0, 0, 0, '', '', '#'),
(3547, '', 0, 0, 0, 0, '', '', '#'),
(3548, '', 0, 0, 0, 0, '', '', '#'),
(3549, '', 0, 0, 0, 0, '', '', '#'),
(3550, '', 0, 0, 0, 0, '', '', '#'),
(3551, '', 0, 0, 0, 0, '', '', '#'),
(4010, '', 0, 0, 0, 0, '', '', '#'),
(4011, '', 0, 0, 0, 0, '', '', '#'),
(5000, 'Policy Management', '3', '0', '0', '25', NULL, NULL, NULL),
(5001, 'New Policy', '3', '5000', '0', '25', NULL, NULL, 'new-policy.php'),
(5002, 'Manage Policy', '3', '5000', '0', '25', NULL, NULL, 'manage-policy.php'),
(5003, 'New Policy Return', '3', '5000', '0', '25', NULL, NULL, 'new-policy-return.php'),
(5004, 'Manage Policy Return', '3', '5000', '0', '25', NULL, NULL, 'manage-policy-return.php'),
(5005, 'New Manual Policy', '3', '5000', '0', '25', NULL, NULL, 'new-manual-policy.php'),
(5006, 'Manage Manual Policy', '3', '5000', '0', '25', NULL, NULL, 'manage-manual-policy.php'),
(5007, 'New Manual Policy Return', '3', '5000', '0', '25', NULL, NULL, 'new-manual-policy-return.php'),
(5009, 'Manage Manual Policy Return', '3', '5000', '0', '25', NULL, NULL, 'manage-manual-policy-return.php'),
(5010, 'Task', '0', '0', '0', '55', NULL, NULL, NULL),
(5011, 'New Task', '1', '5010', '1', '55', 'new-task.php', NULL, NULL),
(5012, 'Manage Tasks', '1', '5010', '1', '55', 'manage-task.php', NULL, NULL),
(5013, 'Audit Trails', '1', '1', '0', '1', NULL, NULL, NULL),
(5014, 'Finance (Dashboard)', '1', '1', '0', '1', NULL, NULL, NULL),
(5015, 'Invoices Due (Receipts)', '2', '5014', '0', '1', NULL, NULL, NULL),
(5016, 'Invoices Due (Payments)', '2', '5014', '0', '1', NULL, NULL, NULL),
(5017, 'PDC (In Bound)', '2', '5014', '0', '1', NULL, NULL, NULL),
(5018, 'PDC (Out Bound)', '2', '5014', '0', '1', NULL, NULL, NULL),
(5019, 'Sales Progress Report', 2, 1, 0, 9, '#', NULL, NULL),
(5020, 'Developer Progress Report', 2, 1, 0, 9, '#', NULL, NULL),
(5021, 'Warehouse Category Stock Summary Report', 3, 0, 0, 7, 'report-warehouse-inventory-valuation60.php', 'report-warehouse-inventory-valuation60.php ', NULL),
(5022, 'Attendance Request', 3, 488, 1, 9, 'attendance-request.php', NULL, NULL),
(5024, 'Manage Attendance Request', 3, 488, 0, 9, 'manage-attendance-request.php', NULL, NULL),
(5301, 'Attendance Change (Bulk)', 3, 488, 1, 9, 'attendance-change-bulk.php', NULL, NULL),
(5302, 'Attendance Change Approval', 3, 488, 1, 9, 'attendance-change-approvals.php', NULL, NULL),
(5303, 'Attendance Change HR', 3, 488, 1, 9, 'attendance-change-hr.php', NULL, NULL),
(5305, 'Leave Approvals', 3, 624, 1, 9, 'leave-approvals.php', NULL, NULL),
(5306, 'Leave HR Approvals', 3, 624, 1, 9, 'leave-hr.php', NULL, NULL),
(5311, 'Rotation Approvals', 3, 624, 1, 9, 'rotation-approvals.php', NULL, NULL),
(5312, 'Rotation HR Approvals', 3, 624, 1, 9, 'rotation-hr.php', NULL, NULL),
(5313, 'Rotation Requests List', 3, 624, 1, 9, 'rotation-request-list.php', NULL, NULL),
(5314, 'Rejected Requests', 3, 624, 1, 9, 'rejection-center.php', NULL, NULL),
(6487, 'Bulk Leave Update', 3, 624, 1, 9, 'employee-bulk-leaves.php', NULL, NULL),
(5025, 'Manage Sample', 2, 2012, 0, 19, 'manage-qc-analysis.php', NULL, NULL),
(5026, 'Manage Truck Entry', 2, 2004, 0, 19, 'manage-truck-entry.php', NULL, NULL),
(5027, 'FOC Dispatch Report', 3, 620, 0, 1, 'foc-dispatch.php', NULL, NULL),
(5046, 'Manage Pending Reservation', 2, 6106, 0, 21, 'manage-pending-reservation.php', NULL, NULL),
(5047, 'Manage Checkin Reservation', 2, 6106, 0, 21, 'manage-checkin-reservation.php', NULL, NULL),
(5048, 'Print Reservation Invoice', 3, 6106, 0, 21, 'print-re.php', NULL, NULL),
(5049, 'Sales Tax Return Report New', 2, 620, 0, 1, 'sales-tax-return-report-new.php', NULL, NULL),
(5050, 'Supplier Alteration Pending', 3, 380, 1, 1, 'supp-alteration-pending.php', NULL, NULL),
(5051, 'Pending Delivery', 3, 380, 1, 1, 'pending-delivery.php', NULL, NULL),
(5052, 'CRM Team Activities', 2, 1, 1, 7, '#', NULL, NULL),
(5053, 'DSR Report (Sales)', 3, 380, 1, 2, 'dsr-sheet-sales.php', NULL, NULL),
(5054, 'Call Summary Report 2', 3, 0, 0, 3, 'call-summary-report-two.php', 'call-summary-report-two.php', NULL),
(5055, 'Indent Reports', 1, 0, 0, 22, '', NULL, NULL),
(5056, 'Quotation Report', 1, 5055, 0, 22, 'report-indent-quotation.php', NULL, NULL),
(5057, 'Indent Report', 1, 5055, 0, 22, 'report-indent-form.php', NULL, NULL),
(5058, 'LC Report', 1, 5055, 0, 22, 'report-lc-form.php', NULL, NULL),
(5059, 'Shipment Report', 1, 5055, 0, 22, 'report-shipment-form.php', NULL, NULL),
(5060, 'Customer Setup List', 1, 5055, 0, 22, 'report-bayer-setup-list.php', NULL, NULL),
(5061, 'Vendor Setup List', 1, 5055, 0, 22, 'report-supplier-setup-list.php', NULL, NULL),
(5062, 'Product Setup List', 1, 5055, 0, 22, 'report-item-setup-list.php', NULL, NULL),
(5063, 'Customer Wise - Product List', 1, 5055, 0, 22, 'report-buyer-wise-product.php', NULL, NULL),
(5064, 'Vendor Wise - Product List', 1, 5055, 0, 22, 'report-supplier-wise-product.php', NULL, NULL),
(5065, 'Product Wise - Customer List', 1, 5055, 0, 22, 'report-product-wise-bayer-list.php', NULL, NULL),
(5066, 'Product Wise - Vendor List', 1, 5055, 0, 22, 'report-product-wise-supplier-list.php', NULL, NULL),
(5067, 'Statistical Reports', 1, 0, 0, 22, '', NULL, NULL),
(5068, 'Quotation Made - Indent Pending', 1, 5067, 0, 22, 'report-quotation-made.php', NULL, NULL),
(5069, 'Indent Made LC/BC Pending Report', 1, 5067, 0, 22, 'report-indent-issuelc-pend.php', NULL, NULL),
(5070, 'LC/BC  Made Shipment Pending  Report', 1, 5067, 0, 22, 'report-indent-lc-issue.php', NULL, NULL),
(5071, 'Shipment Made Payment Pending Report', 1, 5067, 0, 22, 'report-indent-shipment-pendc.php', NULL, NULL),
(5072, 'Commission Received Details', 1, 5067, 0, 22, 'report-indent-commission-recv.php', NULL, NULL),
(5073, 'Guest Report', 2, 1, 0, 1, 'guest_report.php', NULL, NULL),
(5074, 'Item Wise Sales Report', 3, 620, 0, 1, 'item-wise-sales.php', NULL, NULL),
(5075, 'Daily Cash Activity Report', 3, 44, 0, 1, 'ledger-view1.php', NULL, NULL),
(5077, 'Cashier', 2, 1, 0, 11, 'cashier.php', NULL, NULL),
(5078, 'Purchase Invoice Pending', 1, 14, 1, 1, 'manage-pending-purchase.php', NULL, NULL),
(5079, 'Category Wise Target Report - GFI', 3, 609, 0, 2, 'load-sheet1122.php', NULL, NULL),
(5080, 'Target vs Achievement Report Sales Person & Value Wise', 3, 609, 0, 2, 'load-sheet110-new.php', NULL, NULL),
(5081, 'T.O & Discount (Sales) Report', 3, 609, 0, 2, 'load-sheet120.php', NULL, NULL),
(5082, 'DWR Report', 3, 609, 0, 2, 'salesman-route-plan2.php', NULL, NULL),
(5083, 'Order Load Sheet', 3, 719, 0, 2, 'load-sheet9980.php', NULL, NULL),
(5084, 'Order Load Sheet 3', 3, 719, 0, 2, 'load-sheet3000.php', NULL, NULL),
(2477, 'Purchase audit(s) are pending', 3, 719, 0, 2, 'manage-pending-audit.php', NULL, NULL),
(5085, 'Brand Wise Sales Summary Report', 3, 609, 0, 2, 'brand-wise-sales-summary.php', NULL, NULL),
(5086, 'Room / Guest Wise Balance', 2, 1, 0, 1, 'guest-wise-balance-report.php', NULL, NULL),
(5087, '{$subCustomerLabel} Wise Sales Invoice Report', 3, 620, 0, 1, 'subcustomer-wise-si-report.php', NULL, NULL),
(5088, 'Complain Log', 3, 0, 0, 1, '#', NULL, NULL),
(5089, 'Create Complain Log', 3, 0, 0, 1, 'new-complain-tradelink.php', NULL, NULL),
(5202, 'Acknowledged Complain Log', 3, 0, 0, 1, 'manage-acknowledged-cpa-tradelink.php', NULL, NULL),
(5090, 'Material Planning Report (Customized)', 3, 626, 1, 1, 'material-planning-report.php', NULL, NULL),
(5091, 'CRM Dashboard', 2, 1, 0, 7, '#', NULL, NULL),
(5092, 'HR Dashboard', 2, 1, 0, 9, '#', NULL, NULL),
(5093, 'Present Team Dashboard', 2, 1, 0, 9, '#', NULL, NULL),
(5094, 'TASK ASSIGNED TO ME', 2, 1, 0, 9, '#', NULL, NULL),
(5095, 'TASK APPROVAL', 2, 1, 0, 9, '#', NULL, NULL),
(5096, 'TASK REQUESTED', 2, 1, 0, 9, '#', NULL, NULL),
(5097, 'System Progress', 2, 1, 0, 9, '#', NULL, NULL),
(5098, 'QUOTATION IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5099, 'QUOTATION IN REJECTION', 2, 1, 0, 9, '#', NULL, NULL), 
(5100, 'Business Projected (6 Months)', 2, 1, 0, 9, '#', NULL, NULL), 
(5101, 'SALE ORDERS IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5102, 'RECEIPT VOUCHERS IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5103, 'PAYMENT VOUCHERS IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5104, 'GENERAL RECEIPT VOUCHERS IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5105, 'GENERAL PAYMENT VOUCHERS IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5106, 'JOURNAL VOUCHER IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL), 
(5107, 'All Invoices Above 1 Million', 2, 1, 0, 9, '#', NULL, NULL), 
(5108, 'Posted IPO - Invoice not created more than 7 days', 2, 1, 0, 9, '#', NULL, NULL),
(5109, 'Posted IPO Over 1 Million - Invoice not created more than 3 days', 2, 1, 0, 9, '#', NULL, NULL),
(5110, 'Department Wise Receivables / Payables', 2, 1, 0, 9, '#', NULL, NULL),
(5112, 'Inventory Dashboard', 2, 1, 0, 1, '#', NULL, NULL),
(5113, 'STOCK OUT IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL),
(5114, 'PROCUREMENT', 2, 1, 0, 9, '#', NULL, NULL),
(5115, 'PURCHASE REQUISITION IN APPROVAL (Burhan Bhai)', 2, 1, 0, 9, '#', NULL, NULL),
(5116, 'PURCHASE REQUISITION IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL),
(5117, 'PURCHASE ORDERS IN APPROVAL', 2, 1, 0, 9, '#', NULL, NULL),
(5118, 'PURCHASE ORDERS IN REJECTION', 2, 1, 0, 9, '#', NULL, NULL),
(5119, 'Project Budget Estimation', 2, 1, 0, 9, '#', NULL, NULL),
(5120, 'Shipping Status (Grundfos)', 2, 1, 0, 9, '#', NULL, NULL),
(5121, 'Shipping Status', 2, 1, 0, 9, '#', NULL, NULL),
(5122, 'Vendor Invoices Overdue (Above 30 Days)', 2, 1, 0, 9, '#', NULL, NULL),
(5123, 'Cost Center Activity Report (POS)', 3, 620, 1, 11, 'login-summary-report.php', NULL, NULL),
(5124, 'COMPLAIN MODULE', 2, 1, 0, 9, '#', NULL, NULL),
(5125, 'Complain Log (Summary)', 2, 1, 0, 9, '#', NULL, NULL),
(5126, 'Pending Complain List', 2, 1, 0, 9, '#', NULL, NULL),
(5127, 'Inventory Consumption Item Wise', 2, 1, 0, 9, '#', NULL, NULL),
(5128, 'Inventory Consumption Project Wise', 2, 1, 0, 9, '#', NULL, NULL),
(5201, 'Manage Sales Receipts snd', 0, 0, 0, 0, 'sales-payment-snd-receipts.php', NULL, NULL),
(5129, 'Task Management Dashboard', 2, 1, 0, 9, '#', NULL, NULL),
(5130, 'Finance Pending Invoices', 2, 1, 0, 9, '#', NULL, NULL),
(5131, 'Total Departments (Active)', 2, 1, 0, 9, '#', NULL, NULL),
(5132, 'Total Designations (Active)', 2, 1, 0, 9, '#', NULL, NULL),
(5133, 'Total Employees (Active)', 2, 1, 0, 9, '#', NULL, NULL),
(5134, 'Last Payroll Generated', 2, 1, 0, 9, '#', NULL, NULL),
(5135, 'Missing Check-Ins (Today)', 2, 1, 0, 9, '#', NULL, NULL),
(5791, 'Dashboard Task Management Board', 2, 1, 0, 9, '#', NULL, NULL),
(5792, 'Dashboard CRM Progress', 2, 1, 0, 9, '#', NULL, NULL),
(5793, 'Dashboard Complain Workflow', 2, 1, 0, 9, '#', NULL, NULL),
(5137, 'Sales by Item Summary', 3, 1899, 0, 24, 'sales-by-item-summary.php', NULL, NULL),
(5794, 'Dashboard Task Ownership Snapshot', 2, 1, 0, 9, '#', NULL, NULL),
(5795, 'Dashboard Portfolio Status Mix', 2, 1, 0, 9, '#', NULL, NULL),
(5796, 'Dashboard Status Detail Live Counts', 2, 1, 0, 9, '#', NULL, NULL),
(5797, 'Dashboard Budget Versus Spend', 2, 1, 0, 9, '#', NULL, NULL),
(5798, 'Dashboard Billing Versus Receipts', 2, 1, 0, 9, '#', NULL, NULL),
(5799, 'Dashboard Critical Tasks', 2, 1, 0, 9, '#', NULL, NULL),
(5800, 'Dashboard Completed This Month', 2, 1, 0, 9, '#', NULL, NULL),
(5801, 'Dashboard Team Location Access', 2, 1, 0, 9, '#', NULL, NULL),
(5138, 'Collections Report', 3, 1899, 0, 24, 'collections-report.php', NULL, NULL),
(5139, 'Product Tags', 2, 2, 1, 1, 'NULL', NULL, NULL),
(5140, 'New product tag', 3, 5139, 1, 1, 'new-product-tags.php', NULL, NULL),
(5141, 'Manage product tag', 3, 5139, 1, 1, 'manage-product-tags.php', NULL, NULL),
(5142, 'Brand Wise Target Report', 3, 610, 1, 1, 'brand-wise-target.php', NULL, NULL),
(5143, 'Shipping', 1, 0, 0, 1, 'NULL', NULL, NULL),

(5144, 'New Shipping', 2, 5143, 0, 1, 'new-shipping.php?shipping=1', NULL, NULL),
(5145, 'Pending Shipping Invoice', 2, 5143, 0, 1, 'manage-shipping-gpo.php?shipping=1', NULL, NULL),
(5146, 'Shipping List', 2, 5143, 0, 1, 'manage-shipping-order.php?shipping=1', NULL, NULL),
(5147, 'Manage Shipping GRN', 2, 5143, 0, 1, 'manage-shipping-grn.php?shipping=1', NULL, NULL),
(5148, 'View Shipping Invoice', 2, 5143, 0, 1, 'manage-shipping.php?shipping=1', NULL, NULL),

(5149, 'Manual Payroll', 2, 18, 0, 1, 'manual-payroll.php', NULL, NULL),
(5150, 'Manage Manual Payroll', 2, 18, 0, 1, 'manage-manual-payroll.php', NULL, NULL),

(5151, 'Meeting', 1, 0, 1, 1, 'NULL', NULL, NULL),
(5152, 'Set Schedule', 1, 5151, 1, 1, 'scheduler.php', NULL, NULL),
(5153, 'Meeting List', 1, 5151, 1, 1, 'meeting-list.php', NULL, NULL),
(5154, 'Month Wise Customer Sale Report', 3, 620, 1, 1, 'load-sheet15.php', NULL, NULL),
(2411, 'Barcode History Report', 3, 620, 1, 0, 'report-item-barcode-wise-history.php', NULL, NULL),
(5155, 'Multiple Manager Approvals Levels', 3, 620, 1, 1, 'manager-level-settings.php', NULL, NULL),
(5157, 'Sales Person Acheivement Report - GFI', 3, 609, 0, 2, 'load-sheet1123.php', NULL, NULL),
(5156, 'Salesman Amount Wise Target Report', 3, 610, 1, 1, 'salesman-amount-wise-target.php', NULL, NULL),
(5158, 'Distributor Type', 2, 4, 1, 1, 'NULL', NULL, NULL),
(5159, 'New Distributor Type', 3, 5158, 1, 1, 'new-distributor-category.php', NULL, NULL),
(5160, 'Manage Distributor Type', 3, 5158, 1, 1, 'manage-distributor-category.php', NULL, NULL),
(5161, 'Yearly Sales Report', 3, 620, 0, 1, 'yearly-sales-report.php', NULL, NULL),
(5162, 'Stock and Sales Statment', 3, 620, 0, 1, 'stock-sales-sarwana.php', NULL, NULL),
(5163, 'SD Supply Statement', 3, 620, 0, 1, 'supply-statement-sarwana.php', NULL, NULL),
(5164, 'Whole Sales Statement', 3, 620, 0, 1, 'whole-sales-statement-sarwana.php', NULL, NULL),
(5165, 'Retail Sales Statement', 3, 620, 0, 1, 'retail-sales-statement-sarwana.php', NULL, NULL),
(5166, 'LMT Sales Statement', 3, 620, 0, 1, 'lmt-sales-statement-sarwana.php', NULL, NULL),
(5167, 'Acconut Summary For The Month', 3, 620, 0, 1, 'account-summary-sarwana.php', NULL, NULL),
(5168, 'Summery of SR (Market Sales Return)', 3, 620, 0, 1, 'sales-return-sarwana.php', NULL, NULL),
(5169, 'Summery of SR (Damage)', 3, 620, 0, 1, 'damage-return-sarwana.php', NULL, NULL),
(5170, 'SD Towns Recovery Dedails for the Month', 3, 620, 0, 1, 'sd-town-recovery-sarwana.php', NULL, NULL),
(5171, 'Corporate Booker Sales Report', 3, 620, 1, 1, 'corporate-booker-sales-report.php', NULL, NULL),
(5172, 'Digital Invoice Sync Pending', 3, 7, 1, 1, 'digital-invoices-sync.php', NULL, NULL),
(5173, 'Corporate Unserved Customer Report', 3, 620, 1, 1, 'corporate-unserved-customer-report.php', NULL, NULL),
(5174, 'DAILY SALES REPORT', 3, 620, 1, 1, 'daily-sales-report-pakchi.php', NULL, NULL),
(5175, 'Summary Report of DSR', 3, 620, 1, 1, 'summary-report-of-dsr-pakchi.php', NULL, NULL),
(5176, 'Today Recovery Report', 3, 620, 1, 1, 'today-recovery-report-pakchi.php', NULL, NULL),
(5177,'Sales Tax Summary Report', 3, 611, 1, 1, 'load-sheet60.php', NULL, NULL),
(5178,'Secondary Sales Analysis Unit Wise', 3, 611, 1, 1, 'load-sheet-secondary.php', NULL, NULL),
(5179,'Shop History Report', 3, 611, 1, 1, 'report-shop-history.php', NULL, NULL),
(5180,'Product Wise Target vs Achievement Report', 3, 609, 0, 2, 'p-target-achievement-report.php', NULL, NULL),
(5181,'Shop Wise Productivity Report', 3, 609, 0, 2, 'productivity-report-sales.php', NULL, NULL),
(5182,'Brand Distribution Report', 3, 609, 0, 2, 'distribution-brands-sales.php', NULL, NULL),
(5183,'Distributor Wise Salesman sales Report', 3, 609, 0, 2, 'report-distributer-wise-purchase-report-snd.php', NULL, NULL),
(5184,'Route Wise Progress Report', 3, 609, 0, 2, 'load-sheet100.php', NULL, NULL),
(5185,'Distributor Unit Activity List', 3, 609, 0, 2, 'dunit-activity-list.php', NULL, NULL),
(5186,'Stock Distributor Report', 3, 609, 0, 2, 'dwarehouse-unit-activity-report-catwise.php', NULL, NULL),
(5187,'Day Recovery Sheet', 3, 613, 1, 1, 'day-recovery-sheet.php', NULL, NULL),
(5188,'Van load Sheet', 3, 613, 1, 1, 'van-load-sheet.php', NULL, NULL),
(5189,'Daily Expense Sheet', 3, 613, 1, 1, 'report-daily-expense.php', NULL, NULL),
(5190,'Brand / Area Wise Daily Sales Sheet', 3, 613, 1, 1, 'brand-area-wise-daily-report.php', NULL, NULL),
(5191,'Sales Achievement Report', 3, 613, 1, 1, 'report-sales-achievement.php', NULL, NULL),
(5192,'Multi Pricing Price List', 3, 613, 1, 1, 'report-price-list.php', NULL, NULL),
(5193,'Tso Wise Sales Report', 3, 613, 1, 1, 'report-tso-wise-sales.php', NULL, NULL),
(5194,'Tso Wise Sales Target & Call Report', 3, 613, 1, 1, 'report-product-wise-sales-target-callreport.php', NULL, NULL),
(5195,'Distributor Product Sales Value Report', 3, 613, 1, 1, 'report-distributor-product-sales.php', NULL, NULL), 
(5196,'Product Category Wise Target Report', 3, 613, 1, 1, 'load-sheet110.php', NULL, NULL),
(5197,'Sales Summary Report', 3, 613, 1, 1, 'report-sales-summary.php', NULL, NULL),
(5198,'Brand Wise Sales Report', 3, 613, 1, 1, 'brand-wise-sales.php', NULL, NULL),
(5199,'Salesman Wise Target Incentive', 3, 613, 1, 1, 'salesman-wise-target-incentive.php', NULL, NULL),
(5200 ,'Master Order Report', 3, 611, 1, 1, 'master-order-report.php', NULL, NULL),
(6103 ,'Booking Reports', 3, 1, 1, 1, NULL, NULL, NULL),
(6104 ,'Guest Report', 2, 1, 1, 1, 'guest_report.php', NULL, NULL),
(6105 ,'Room / Guest Wise Balance', 2, 1, 1, 1, 'guest-wise-balance-report.php', NULL, NULL),
(6106 ,'Booking (Hotel)', 1, 0, 1, 21, NULL, NULL, NULL),
(6107 ,'New Booking (Hotel)', 2, 6106, 1, 21, 'new-reservation3.php', NULL, NULL),
(6108 ,'Manage Booking (Hotel)', 2, 6106, 1, 21, 'manage-reservation3.php', NULL, NULL),
(6109 ,'Hotel Reports', 2, 6106, 1, 21, NULL, NULL, NULL),
(6110 ,'Booking And Payment Report', 3, 6106, 1, 21, 'booking-report.php', NULL, NULL),
(6111 ,'Performance Report', 3, 6106, 1, 21, 'service-report.php', NULL, NULL),
(6112 ,'Guest Report', 3, 6106, 1, 21, 'guest_report.php', NULL, NULL),
(6113 ,'Daily Cash Activity Report', 3, 6106, 1, 21, 'ledger-view1.php', NULL, NULL),
(6114 ,'Guest Wise Balance Report', 3, 6106, 1, 21, 'guest-wise-balance-report.php', NULL, NULL),
(6115 ,'Material Planning', 3, 11, 0, 8, 'material-planning.php', NULL, NULL),
(6116 ,'Material Planning List', 3, 11, 0, 8, 'material-planning-list.php', NULL, NULL),
(6117 ,'Production Service Charges', 3, 11, 0, 8, 'production-service-charges.php', NULL, NULL), 
(6118, 'Daily Booking vs Execution Report (Pakchi)', 3, 620, 1, 1, 'booking-vs-execution-report-pakchi.php', NULL, NULL),
(6119, 'Sales Tracker Report (Pakchi)', 3, 620, 1, 1, 'sales-tracker-report-pakchi.php', NULL, NULL),
(6120, 'Pending Import GRN', 3, 291, 1, 1, 'manage-pending-igrn.php', NULL, NULL),
(6121, 'Manage Import GRN', 3, 291, 1, 1, 'manage-igrn.php', NULL, NULL),
(6122, 'Submitted Action Form (Approval)', 3, 6106, 0, 21, 'pending-survey-list.php', NULL, NULL),
(6123, 'Pending Booking Payments (Overdue)', 3, 1780, 1, 21, 'manage-pending-payment-overdue.php', NULL, NULL),
(6124, 'Sales Person Target Report - GFI', 3, 609, 0, 2, 'salesman-wise-target-gfi.php', NULL, NULL),
(6125, 'Lead Visit Pending', 3, 24, 1, 21, 'lead-list-musaji.php', NULL, NULL),
(6126, 'Manage Lead Visit', 3, 24, 1, 21, 'manage-lead-musaji.php', NULL, NULL),
(6600, 'Buffet Templates', 2, 1, 1, 11, 'buffet-templates.php', NULL, NULL),
(6601, 'Buffet Planning', 2, 1, 1, 11, 'buffet-planning.php', NULL, NULL),
(6602, 'Buffet Plan List', 2, 1, 1, 11, 'buffet-plan-list.php', NULL, NULL),
(6603, 'Buffet Plan View', 3, 6602, 0, 11, 'buffet-plan-view.php', NULL, NULL),
(6604, 'Item Based FOC (Purchasing)', 2, 5, 1, 1, 'item-foc-purchase.php', NULL, NULL),
(7055, 'Salesman Monthly Sales & Recovery Report', 3, 620, 1, 1, 'salesman-monthly-sales-receovery-report.php', NULL, NULL),
(7056, 'Marketing Person Progress Report', 3, 620, 1, 1, 'marketing-person-progress-report.php', NULL, NULL),
(7057, 'TSO Target Wise Achievement Report (Sarwana)', 3, 620, 0, 1, 'target-vs-ach-sarwana.php', NULL, NULL),
(7058, 'Distributor Target Session', 2, 7, 1, 1, 'create-distributor-session.php', NULL, NULL),
(7059, 'Manage Distributor Target Session', 2, 7, 1, 1, 'manage-distributor-session.php', NULL, NULL),
(7060, 'Net Sales Summary Report (My Choices)', 3, 620, 0, 1, 'sales-report-mychoices.php', NULL, NULL),
(7061, 'Pending Summary (Product Wise) - My Choices', 3, 620, 0, 1, 'pending-summary-product-wise-mychoice.php', NULL, NULL),
(7062, 'Transportions Summary Report - My Choices', 3, 620, 0, 1, 'transportions-summary-report-mychoice.php', NULL, NULL),
(7063, 'Delivery Challan Register Osaka', 3, 620, 1, 1, 'delivery-challan-register-osaka.php', NULL, NULL),
(7064, 'Aging Report New (SND)', 3, 609, 1, 2, 'report-sales-new.php', NULL, NULL),
(7065, 'Policy Sales Report', 3, 5000, 1, 25, 'policy-sales-report.php', NULL, NULL),
(7066, 'Manual Policy Report', 3, 5000, 1, 25, 'manual-policy-report.php', NULL, NULL),
(7067, 'Policy Report', 3, 5000, 1, 25, 'policy-report.php', NULL, NULL),
(7068, 'Policy Return Report', 3, 5000, 1, 25, 'return-policy-report.php', NULL, NULL),
(7069, 'Production / Policy Report', 3, 5000, 1, 25, 'production-policy-report.php', NULL, NULL),
(7070, 'Production / Policy Report (Return)', 3, 5000, 1, 25, 'production-policy-report-return.php', NULL, NULL),
(7071, 'Create Direct Invoice', '3', '5000', '0', '25', NULL, NULL, 'new-direct-invoice.php'),
(7072, 'Manage Direct Invoices', '3', '5000', '0', '25', NULL, NULL, 'manage-direct-invoices.php'),
(7073, 'Create Return Invoice', '3', '5000', '0', '25', NULL, NULL, 'new-return-direct-invoice.php'),
(7074, 'Manage Return Invoices', '3', '5000', '0', '25', NULL, NULL, 'manage-return-direct-invoices.php'),
(7075, 'Product Slab Discount', 2, 2, 1, 1, 'qty-wise-discount.php', NULL, NULL),
(7076, 'Cash Flow Statement', 3, 44, 1, 1, 'cash-flow-statement.php', NULL, NULL),
(7077, 'Product FOC Report', 3, 609, 1, 1, 'product-foc-report.php', NULL, NULL),
(7078, 'Potential Report', 3, 609, 1, 1, 'potential-report.php', NULL, NULL),
(7079, 'Sales Journal Razik', 3, 621, 1, 1, 'sales-journal-razik.php', NULL, NULL),
(7080, 'Report Warehouse Inventory Valuation Razik', 3, 621, 1, 1, 'report-warehouse-inventory-valuation-razik.php', NULL, NULL),
(7081, 'Report Item List3 Razik', 3, 621, 1, 1, 'report-item-list3-razik.php', NULL, NULL),
(7082, 'Sales Journal Customer Wise Razik', 3, 621, 1, 1, 'sales-journal-customer-wise-razik.php', NULL, NULL),
(7083, 'Report Voucher Date Wise', 3, 621, 1, 1, 'report-voucher-date-wise.php', NULL, NULL),
(7084, 'Report Item Sales Summary', 3, 621, 1, 1, 'report-item-sales-summary.php', NULL, NULL),
(7085, 'Report Product Ledger Razik', 3, 621, 1, 1, 'report-product-ledger-razik.php', NULL, NULL),
(7086, 'Daily Sales Journal', 3, 620, 1, 1, 'daily-sales-journal.php', NULL, NULL),
(7087, 'Sales Tax Customer Report', 3, 620, 1, 1, 'sales-tax-customer-report.php', NULL, NULL),
(7088, 'Purchase Tax Vendor Report', 3, 620, 1, 1, 'purchase-tax-vendor-report.php', NULL, NULL),
(7089, 'Salesman Accounts Receivable', 3, 620, 0, 1, 'salesman-accounts-receivable.php', NULL, NULL),
(7090, 'Grower Sheet', 1, 0, 0, 2, 'grower-sheet.php', NULL, NULL),
(7091, 'Fas Sheet', 1, 0, 0, 2, 'fas-sheet.php', NULL, NULL),
(7092, '1 Many Sheet', 1, 0, 0, 2, '1_many-sheet.php', NULL, NULL),
(7093, 'Daily Consumption Sheet', 1, 0, 0, 2, 'daily-consumption-sheet.php', NULL, NULL),
(7094, 'Demo Plot Sheet', 1, 0, 0, 2, 'demo-plot-sheet.php', NULL, NULL),
(7095, 'Fas Monthwise Sheet', 1, 0, 0, 2, 'fas-monthwise-sheet.php', NULL, NULL),
(7096, 'Fas Datewise Sheet', 1, 0, 0, 2, 'fas-datewise-sheet.php', NULL, NULL),
(7097, 'Demo Plat Monthwise Sheet', 1, 0, 0, 2, 'demo-plat-monthwise-sheet.php', NULL, NULL),
(7098, 'Demo Plat Datewise Sheet', 1, 0, 0, 2, 'demo-plat-datewise-sheet.php', NULL, NULL),
(7099, 'Report Opper Detail', 1, 0, 0, 2, 'report-opper-detail.php', NULL, NULL),
(7100, 'Stock Aging Report2', 1, 0, 0, 2, 'stock-aging-report2.php', NULL, NULL),
(7101, 'Stock Aging Report3', 1, 0, 0, 2, 'stock-aging-report3.php', NULL, NULL),
(7102, 'Stock Aging Report7', 1, 0, 0, 2, 'stock-aging-report7.php', NULL, NULL),
(7103, 'Stock Aging Report8', 1, 0, 0, 2, 'stock-aging-report8.php', NULL, NULL),
(7104, 'Report Item List3', 1, 0, 0, 2, 'report-item-list3.php', NULL, NULL),
(7105, 'Master Order Report', 3, 620, 1, 1, 'master-order-report.php', NULL, NULL),
(7106, 'Order Sheet', 3, 620, 1, 1, 'order-sheet.php', NULL, NULL),
(7107, 'Progress Sheet', 2, 1, 0, 9, 'progress-sheet.php', NULL, NULL),
(7108, 'Delivery Sheet Month Wise', 2, 1, 0, 9, 'delivery-sheet-month-wise.php', NULL, NULL),
(7109, 'Salesman Wise Target Vs Ach', 3, 620, 1, 1, 'salesman-wise-target-vs-ach.php', NULL, NULL),
(7110, 'Manager Progress Report', 3, 620, 1, 1, 'manager-progress-report.php', NULL, NULL),
(7111, 'Dsr Sheet1', 3, 608, 0, 2, 'dsr-sheet1.php', NULL, NULL),
(7112, 'Dsr Sheet2', 3, 608, 0, 2, 'dsr-sheet2.php', NULL, NULL),
(7113, 'Dsr Sheet3', 3, 608, 0, 2, 'dsr-sheet3.php', NULL, NULL),
(7114, 'Dsr Sheet4', 3, 608, 0, 2, 'dsr-sheet4.php', NULL, NULL),
(7115, 'Dsr Sheet5', 3, 608, 0, 2, 'dsr-sheet5.php', NULL, NULL),
(7116, 'Dsr Sheet6', 3, 608, 0, 2, 'dsr-sheet6.php', NULL, NULL),
(7117, 'Load Sheet13', 3, 609, 0, 2, 'load-sheet13.php', NULL, NULL),
(7118, 'Report Project Progress3', 3, 931, 1, 1, 'report-project-progress3.php', NULL, NULL),
(7119, 'Report Project Progress2', 3, 931, 1, 1, 'report-project-progress2.php', NULL, NULL),
(7120, 'Delivery Content Report', 2, 620, 1, 1, 'delivery-content-report.php', NULL, NULL),
(7121, 'Report Sale Pur Recurring', 3, 620, 1, 1, 'report-sale-pur-recurring.php', NULL, NULL),
(7122, 'Report Sales Discount', 3, 620, 1, 1, 'report-sales-discount.php', NULL, NULL),
(7123, 'Sales Journal New', 3, 620, 1, 1, 'sales-journal-new.php', NULL, NULL),
(7124, 'Item Party Wise Sales Report', 3, 620, 1, 1, 'Item-Party-Wise-Sales-Report.php', NULL, NULL),
(7125, 'Invoice View Report', 3, 620, 1, 1, 'invoice-view-report.php', NULL, NULL),
(7126, 'Sales Tax Goods Report New', 2, 620, 1, 1, 'sales-tax-goods-report-new.php', NULL, NULL),
(7127, 'Incentive Report With Sale', 3, 620, 1, 1, 'incentive_report_with_sale.php', NULL, NULL),
(7128, 'Incentive Report With Zone', 3, 620, 1, 1, 'incentive_report_with_zone.php', NULL, NULL),
(7129, 'Report Customer List New', 3, 618, 1, 1, 'report-customer-list-new.php', NULL, NULL),
(7130, 'Bank Report Off Record', 3, 0, 0, 7, 'bank-report-off-record.php', NULL, NULL),
(7131, 'Stock Aging Report Asset', 3, 931, 1, 1, 'stock-aging-report_asset.php', NULL, NULL),
(7132, 'Report Item Deprecia Detail', 3, 931, 1, 1, 'report-item-deprecia-detail.php', NULL, NULL),
(7133, 'Report Item Depreciation', 3, 931, 1, 1, 'report-item-depreciation.php', NULL, NULL),
(7134, 'Report Item Deprecia Summary', 3, 931, 1, 1, 'report-item-deprecia-summary.php', NULL, NULL),
(7135, 'Report Warehouse Inventory Depar Val6', 3, 931, 1, 1, 'report-warehouse-inventory-depar-val6.php', NULL, NULL),
(7136, 'Report Warehouse Inventory User Val6', 3, 931, 1, 1, 'report-warehouse-inventory-user-val6.php', NULL, NULL),
(7137, 'Broker Builty Report', 3, 626, 1, 1, 'broker-builty-report.php', NULL, NULL),
(7138, 'Bilties Item Wise Report', 3, 626, 1, 1, 'bilties-item-wise-report.php', NULL, NULL),
(7139, 'Brokery Report', 3, 626, 1, 1, 'brokery-report.php', NULL, NULL),
(7140, 'Report Purchase Vendor', 3, 620, 1, 1, 'report-purchase-vendor.php', NULL, NULL),
(7141, 'Report Purchase Duties Vendor', 3, 620, 1, 1, 'report-purchase-duties-vendor.php', NULL, NULL),
(7142, 'Report Workorder Balance', 2, 626, 0, 2, 'report-workorder-balance.php', NULL, NULL),
(7143, 'Report Workorder Ledger', 2, 626, 0, 2, 'report-workorder-ledger.php', NULL, NULL),
(7144, 'Report Nonstock Balance', 2, 626, 0, 2, 'report-nonstock-balance.php', NULL, NULL),
(7145, 'Bom Importer Report', 2, 1899, 0, 8, 'bom-importer-report.php', NULL, NULL),
(7146, 'Bom Stock Report', 2, 1899, 0, 8, 'bom-stock-report.php', NULL, NULL),
(7147, 'Report Production Sheet20', 3, 1389, 1, 8, 'report-production-sheet20.php', NULL, NULL),
(7148, 'Material Issue Report', 3, 620, 1, 1, 'material-issue-report.php', NULL, NULL),
(7149, 'Report Warehouse Rm Stock', 3, 620, 1, 1, 'report-warehouse-rm-stock.php', NULL, NULL),
(7150, 'Stock Movement Report', 3, 627, 0, 1, 'stock-movement-report.php', NULL, NULL),
(7151, 'Stock Claimed Summary Report', 3, 627, 0, 1, 'stock-claimed-summary-report.php', NULL, NULL),
(7152, 'Report Import Duties', 3, 620, 1, 1, 'report-import-duties.php', NULL, NULL),
(7153, 'Report Daily Supplier Rate', 3, 620, 1, 1, 'report-daily-supplier-rate.php', NULL, NULL),
(7154, 'Report Cb Brand Discount', 3, 618, 1, 1, 'report-cb-brand-discount.php', NULL, NULL),
(7155, 'Report Employee Leaves2', 3, 624, 1, 9, 'report-employee-leaves2.php', NULL, NULL),
(7156, 'Order Shipment Report', 3, 1899, 0, 24, 'order-shipment-report.php', NULL, NULL),
(7157, 'Report Dailyactivity', 3, 623, 1, 1, 'report-dailyactivity.php', NULL, NULL),
(7158, 'Report Manage Pending Payment', 3, 1359, 1, 1, 'report-manage-pending-payment.php', NULL, NULL),
(7159, 'Report Manage Pending Payment2', 3, 1359, 1, 1, 'report-manage-pending-payment2.php', NULL, NULL),
(7160, 'Report Manage Pending Units', 3, 1359, 1, 1, 'report-manage-pending-units.php', NULL, NULL),
(7161, 'Report Unit Wise Booking Sheet', 3, 1359, 1, 1, 'report-unit-wise-booking-sheet.php', NULL, NULL),
(7162, 'Quotation Report', 3, 5052, 1, 7, 'report-quotation-sama.php', NULL, NULL),
(7163, 'Account Statement', 3, 44, 1, 1, 'account-statement.php', NULL, NULL),
(7164, 'Bank Statement', 3, 44, 1, 1, 'bank-statement.php', NULL, NULL),

(7165,'Distributor Wise Purchase Pending Report', 3, 609, 0, 2, 'report-distributer-wise-purchase-report-pending-snd.php', NULL, NULL),
(2403, 'Receivable Summary Report ', 3, 2402, 1, 2, 'receivable-summary-report.php', NULL, NULL)";

 $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn) );

 $data20 = mysqli_query($conn,"SELECT  * from temp_system_pages order by id ") or die(mysqli_error($conn));  
 while($info20 = mysqli_fetch_array( $data20 )) { 

$p0 = $info20['id'];
$p1 = $info20['page_label'];
$p2 = $info20['access_heirarchy'];
$p3 = $info20['parent'];
$p4 = $info20['enable'];
$p5 = $info20['type'];
$p6 = $info20['link'];
$p7 = $info20['log_link'];
$p8 = $info20['log_name'];

if($current_company=='') $current_company=1;
$current_company = (int)$current_company;

if ($companyScopeReady) {
 $sql = "INSERT INTO system_pages
(`id`, page_label, access_heirarchy, `parent`, `enable`, `type`, link, log_link, log_name, company_id )
VALUES ('$p0','$p1','$p2','$p3','$p4','$p5','$p6','$p7','$p8', '$current_company' )
ON DUPLICATE KEY UPDATE
page_label=VALUES(page_label),
access_heirarchy=VALUES(access_heirarchy),
`parent`=VALUES(`parent`),
`enable`=VALUES(`enable`),
`type`=VALUES(`type`),
link=VALUES(link),
log_link=VALUES(log_link),
log_name=VALUES(log_name),
company_id=VALUES(company_id)" ;
} else {
 $sql = "INSERT INTO system_pages
(`id`, page_label, access_heirarchy, `parent`, `enable`, `type`, link, log_link, log_name, company_id )
VALUES ('$p0','$p1','$p2','$p3','$p4','$p5','$p6','$p7','$p8', '$current_company' )
ON DUPLICATE KEY UPDATE
page_label=IF(company_id=VALUES(company_id), VALUES(page_label), page_label),
access_heirarchy=IF(company_id=VALUES(company_id), VALUES(access_heirarchy), access_heirarchy),
`parent`=IF(company_id=VALUES(company_id), VALUES(`parent`), `parent`),
`enable`=IF(company_id=VALUES(company_id), VALUES(`enable`), `enable`),
`type`=IF(company_id=VALUES(company_id), VALUES(`type`), `type`),
link=IF(company_id=VALUES(company_id), VALUES(link), link),
log_link=IF(company_id=VALUES(company_id), VALUES(log_link), log_link),
log_name=IF(company_id=VALUES(company_id), VALUES(log_name), log_name)" ;
}
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

 }
    $query ="DROP TEMPORARY TABLE IF EXISTS temp_system_pages";
    $retval = mysqli_query($conn, $query ) or die(mysqli_error($conn) );

    return $companyScopeReady;
}

function test_input($data)
{
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = test_input($value); // recursive call
        }
        return $data;
    } else {
        // $data = trim($data);
        $data = stripslashes($data);
        // $data = htmlspecialchars($data);
        $data = preg_replace('/[^A-Za-z0-9\-?!@=,+%#$&:()*\/\|.]/', ' ', $data);
        return $data;
    }
}

// function test_input($data)
// {
// //  $data = trim($data);
//  $data = stripslashes($data);
// //  $data = htmlspecialchars($data);
//   $data =  preg_replace('/[^A-Za-z0-9\-?!@=,+%#$&:()*\/\|.]/ ', ' ', $data);
//   return $data;
// }

function test_input2($data)
{
//  $data = trim($data);
 $data = stripslashes($data);
//  $data = htmlspecialchars($data);
  $data =  preg_replace('[^A-Za-z0-9\-?!@=,+%#$&:()*.] ', ' ', $data);
  return $data;
}


function indexExists($conn, $table, $index) {
    $query = "SELECT COUNT(1) IndexIsThere
              FROM information_schema.statistics
              WHERE table_schema = '$dbname'
              AND table_name = '$table'
              AND index_name = '$index'";
    $result = $conn->query($query);
    $row = $result->fetch_assoc();
    return $row['IndexIsThere'] > 0;
}

function nextlineinput($data)
{
$data = str_replace('  ', '&#10;', ($data));
return $data;

}

function nextline($data)
{
$data = str_replace(' 
                                            ', '<br />', ($data));
$data = str_replace('
                   ', '<br />', ($data));
$data = str_replace('
                   ', '<br />', ($data));
$data = str_replace(' 	           	', '<br />', ($data));
$data = str_replace('  ', '<br />', ($data));
return $data;

}


function employee_lastdate()
{
//  $data = trim($data);

  global $conn; 

 $data4 = mysqli_query($conn,"SELECT * from employee  ") or die(mysqli_error($conn)); 

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 $emp = $info4['id'];
 $year_date = $info4['year_date'];
 

$date = new DateTime($year_date);
$now = new DateTime();

if($date >= $now) {
      $policy_id = mysqli_get_var("Update employee set year_date='$year_date' where  id='$emp' "); 
}

 }

}


function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}



function GetImageExtension($imagetype)
     {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
       case 'image/jpg': return '.jpg';
           case 'image/png': return '.png';
           default: return false;
       }
     }



function GetImageExtension2($imagetype)
     {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
       
       

           case 'application/pdf': return '.pdf';
           case 'application/msword': return '.doc';
       case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
       case 'image/jpg': return '.jpg';
           case 'image/png': return '.png';
        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': return '.docx';
           case 'image/jpeg': return '.jpg';
       default: return false;
       }
     }



function customeroldreceivable($cid,$days = NULL)
     {


        global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
        if(isset($info2000['customervendor_same']) && (int)$info2000['customervendor_same'] === 1){
            return customeroldreceivablemulticurrency($cid);
        }
        
        if($days == NULL){
            $days = '';
        }else{
            $days = " AND datetime < NOW() - INTERVAL '$days' DAY";
        }

        $data34 = mysqli_query($conn,"SELECT SUM(pending_amount) as sum FROM sales WHERE customer_id='$cid' $days") or die(mysqli_error($conn));       
        $info34 = mysqli_fetch_array( $data34 );

        $data40 = mysqli_query($conn,"SELECT SUM(advance_payment) as sum FROM customer WHERE id='$cid'") or die(mysqli_error($conn));      
        $info40 = mysqli_fetch_array( $data40 );
        $data38 = mysqli_query($conn,"SELECT SUM(pending_amount) as sum FROM sales_debit_note WHERE cid='$cid'") or die(mysqli_error($conn));      
        $info38 = mysqli_fetch_array( $data38 );
        $data36 = mysqli_query($conn,"SELECT ob FROM customer WHERE id='$cid'") or die(mysqli_error($conn));       
        $info36 = mysqli_fetch_array( $data36 );
        

        $tot= $info34['sum']+$info38['sum'] - $info40['sum'] + $info36['ob']+$so_limit;

        if($tot=='') $tot=0;

       return $tot;
     }
function customeroldreceivablesnd($cid,$days = NULL,$date = NULL)
     {


        global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
        
        if($days == NULL){
            $days = '';
        }else{
            $days = " AND datetime < NOW() - INTERVAL '$days' DAY";
        }
        
        if($date == NULL){
            $date = '';
        }

        $data34 = mysqli_query($conn,"SELECT SUM(total) as sum FROM so WHERE  customer_id='$cid' AND order_delete=0 AND execute_complete = 1 $days $date") or die(mysqli_error($conn));       
        $info34 = mysqli_fetch_array( $data34 );
        $data35 = mysqli_query($conn,"SELECT SUM(total) as sum FROM so_return WHERE  customer_id='$cid' AND order_delete=0 AND execute_complete = 1 $days $date") or die(mysqli_error($conn));       
        $info35 = mysqli_fetch_array( $data35 );

        $data40 = mysqli_query($conn,"SELECT SUM(advance_payment) as sum FROM customer WHERE id='$cid'") or die(mysqli_error($conn));      
        $info40 = mysqli_fetch_array( $data40 );
        $data38 = mysqli_query($conn,"SELECT SUM(pending_amount) as sum FROM sales_debit_note WHERE cid='$cid'") or die(mysqli_error($conn));      
        $info38 = mysqli_fetch_array( $data38 );
        $data36 = mysqli_query($conn,"SELECT ob FROM customer WHERE id='$cid'") or die(mysqli_error($conn));       
        $info36 = mysqli_fetch_array( $data36 );
        $tot= $info34['sum']+$info38['sum'] - $info40['sum'] + $info36['ob']+$so_limit- $info35['sum'] ;

        if($tot=='') $tot=0;

       return $tot;
     }

// Basit
function customeroldreceivablemulticurrency($cid) {
    global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
    
    $total_balance = 0;

    // Sales (SI)
    $data15 = mysqli_query($conn,"SELECT sum(total/currency_rate) as sum from sales where customer_id='$cid'") or die(mysqli_error($conn));
    $info15 = mysqli_fetch_array($data15);
    $total_balance += $info15['sum'];

    // Sales Debit Note
    $data240 = mysqli_query($conn,"SELECT sum(total) as sum from sales_debit_note where cid='$cid'") or die(mysqli_error($conn));
    $info240 = mysqli_fetch_array($data240);
    $total_balance += $info240['sum'];

    // Sales Return (SR)
    $data16 = mysqli_query($conn,"SELECT sum(total_amount/currency_rate) as sum from sales_return where customer_id='$cid'") or die(mysqli_error($conn));
    $info16 = mysqli_fetch_array($data16);
    $total_balance -= $info16['sum'];

    // Cash Transactions (customer payments)
    $data160 = mysqli_query($conn,"SELECT sum((debit-credit)/currency_rate) as sum from cash_transaction where user_id='$cid' AND user_type=1 && `show`=1 && (debit!=0 || credit!=0)") or die(mysqli_error($conn));
    $info160 = mysqli_fetch_array($data160);
    if($info160['sum'] > 0) {
        $total_balance += $info160['sum'];
    } else {
        $ss = $info160['sum']*(-1);
        $total_balance -= $ss;
    }

    // Sales Credit Note
    $data16 = mysqli_query($conn,"SELECT sum(total) as sum from sales_credit_note where cid='$cid'") or die(mysqli_error($conn));
    $info16 = mysqli_fetch_array($data16);
    $total_balance -= $info16['sum'];

    // Payment Received
    $data17 = mysqli_query($conn,"SELECT sum(amount/currency_rate) as sum from payment_received where cid='$cid'") or die(mysqli_error($conn));
    $info17 = mysqli_fetch_array($data17);
    $total_balance -= $info17['sum'];

    // Opening Balance
    $data18 = mysqli_query($conn,"SELECT sum(oba) as sum from customer where id='$cid'") or die(mysqli_error($conn));
    $info18 = mysqli_fetch_array($data18);
    $total_balance += $info18['sum'];

    // Purchasing (PI) - This reduces receivable as it's vendor side
    $data15 = mysqli_query($conn,"SELECT sum(total_amount/currency_rate) as sum from purchasing where vendor_id='$cid'") or die(mysqli_error($conn));
    $info15 = mysqli_fetch_array($data15);
    $total_balance -= $info15['sum'];

    // Purchase Debit Note
    $data240 = mysqli_query($conn,"SELECT sum(total) as sum from purchase_debit_note where vid='$cid'") or die(mysqli_error($conn));
    $info240 = mysqli_fetch_array($data240);
    $total_balance -= $info240['sum'];

    // Purchase Returns
    $data16 = mysqli_query($conn,"SELECT sum(total_amount/currency_rate) as sum from purchase_returns where vendor_id='$cid'") or die(mysqli_error($conn));
    $info16 = mysqli_fetch_array($data16);
    $total_balance += $info16['sum'];

    // Purchase Credit Note
    $data16 = mysqli_query($conn,"SELECT sum(total) as sum from purchase_credit_note where vid='$cid'") or die(mysqli_error($conn));
    $info16 = mysqli_fetch_array($data16);
    $total_balance += $info16['sum'];

    // Payment Sent
    $data17 = mysqli_query($conn,"SELECT sum(amount/currency_rate) as sum from payment_sent where vid='$cid'") or die(mysqli_error($conn));
    $info17 = mysqli_fetch_array($data17);
    $total_balance += $info17['sum'];

    // Vendor Opening Balance
    $data18 = mysqli_query($conn,"SELECT sum(oba) as sum from vendor where id='$cid'") or die(mysqli_error($conn));
    $info18 = mysqli_fetch_array($data18);
    $total_balance -= $info18['sum'];

    // Cash Transactions (vendor payments)
    $data160 = mysqli_query($conn,"SELECT sum((credit-debit)/currency_rate) as sum from cash_transaction where user_id='$cid' AND user_type=2 && `show`=1 && (debit!=0 || credit!=0)") or die(mysqli_error($conn));
    $info160 = mysqli_fetch_array($data160);
    if($info160['sum'] > 0) {
        $total_balance += $info160['sum'];
    } else {
        $ss = $info160['sum']*(-1);
        $total_balance -= $ss;
    }

    return $total_balance ? $total_balance : 0;
}


    // Hamza
    // When Customer and vendor same so it work 
    function dealerreceivable($cid,$days = null){
        global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
        
        if($days == NULL || $days == 0){
            $days = '';
        }else{
            $days = " AND datetime < NOW() - INTERVAL '$days' DAY";
        }

        //customer
       $data34 = mysqli_query($conn,"SELECT SUM(total) as sum FROM sales WHERE customer_id='$cid' $days") or die(mysqli_error($conn));
        $info34 = mysqli_fetch_array( $data34 );
        
        $data38 = mysqli_query($conn,"SELECT SUM(total) as sum FROM sales_debit_note WHERE cid='$cid'") or die(mysqli_error($conn));
        $info38 = mysqli_fetch_array( $data38 );
        
        $data36 = mysqli_query($conn,"SELECT oba FROM customer WHERE id='$cid'") or die(mysqli_error($conn));       
        $info36 = mysqli_fetch_array( $data36 );
        
        $data37 = mysqli_query($conn,"SELECT sum(total_amount) as sum from sales_return WHERE customer_id IN ($cid)");
        $info37 = mysqli_fetch_array( $data37 );
        
        $data39 = mysqli_query($conn,"SELECT sum(amount) as sum from payment_received WHERE cid ='$cid'");
        $info39 = mysqli_fetch_array( $data39 );
        
        $tot=  $info34['sum'] + $info38['sum']  + $info36['oba'] - $info37['sum'] - $info39['sum'] +$so_limit;
        
        if($tot=='') $tot=0;
        //customer end
        
        //Vendor
        $data34 = mysqli_query($conn,"SELECT SUM(total_amount) as sum FROM purchasing WHERE vendor_id='$cid'") or die(mysqli_error($conn));       
        $info34 = mysqli_fetch_array( $data34 );
        
        $data38 = mysqli_query($conn,"SELECT SUM(total) as sum FROM purchase_credit_note WHERE vid='$cid'") or die(mysqli_error($conn));      
        $info38 = mysqli_fetch_array( $data38 );
        $data36 = mysqli_query($conn,"SELECT oba FROM vendor WHERE id='$cid'") or die(mysqli_error($conn));       
        $info36 = mysqli_fetch_array( $data36 );
        
        $data365 = mysqli_query($conn,"SELECT sum(total_amount) as total FROM purchase_returns WHERE vendor_id='$cid'") or die(mysqli_error($conn));       
        $info365 = mysqli_fetch_array( $data365 );
        
        $data366 = mysqli_query($conn,"SELECT sum(amount) as total FROM payment_sent WHERE vid = '$cid'") or die(mysqli_error($conn));       
        $info366 = mysqli_fetch_array( $data366 );
        
        $tot2= $info34['sum']+$info38['sum'] + $info36['oba']-$info365['total'] - $info366['total'] +$so_limit;
        if($tot2=='') $tot2=0;
        //Vendor end
    
        return $tot - $tot2 ;
        
    }
    // Hamza end
function vendoroldpayable($cid)
     {


        global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
        if(isset($info2000['customervendor_same']) && (int)$info2000['customervendor_same'] === 1){
            return customeroldreceivablemulticurrency($cid);
        }
 

       $data34 = mysqli_query($conn,"SELECT SUM(pending_amount) as sum FROM purchasing WHERE vendor_id='$cid'") or die(mysqli_error($conn));       
$info34 = mysqli_fetch_array( $data34 );

$data40 = mysqli_query($conn,"SELECT SUM(advance_payment) as sum FROM vendor WHERE id='$cid'") or die(mysqli_error($conn));      
$info40 = mysqli_fetch_array( $data40 );
$data38 = mysqli_query($conn,"SELECT SUM(pending_amount) as sum FROM purchase_credit_note WHERE vid='$cid'") or die(mysqli_error($conn));      
$info38 = mysqli_fetch_array( $data38 );
$data36 = mysqli_query($conn,"SELECT ob FROM vendor WHERE id='$cid'") or die(mysqli_error($conn));       
$info36 = mysqli_fetch_array( $data36 );
$tot= $info34['sum']+$info38['sum'] - $info40['sum'] + $info36['ob']+$so_limit;

if($tot=='') $tot=0;

       return $tot;
     }



   


if($info1000['customer_sms']==1 || $info2000['vendor_sms']==1 ||  $info1000['admin_sms']==1)
{

$username   = $info3000['sms_username']; // your username
$password   = $info3000['sms_password']; // your Password
$brandname = $info3000['sms_brand']; // your Password
$smsurl     = $info4000['sms_link']."".$info3000['sms_api'];

########################################################
# Functions used to send the SMS message
########################################################
    function httpRequest($url)
    {
        $args;
        $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
        preg_match($pattern,$url,$args);
        $in = "";
        $fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
        if (!$fp)
        {
           return("$errstr ($errno)");
        }
        else
        {
            $out = "GET /$args[3] HTTP/1.1\r\n";
            $out .= "Host: $args[1]:$args[2]\r\n";
            $out .= "User-agent: PHP Web SMS client\r\n";
            $out .= "Accept: */*\r\n";
            $out .= "Connection: Close\r\n\r\n";

            fwrite($fp, $out);
            while (!feof($fp))
            {
               $in.=fgets($fp, 128);
            }
        }
        fclose($fp);
        return($in);
    }
    
  

  

  
      function send_sms($phone, $msg, $debug=false)
    {

        global $conn,$username,$password,$smsurl,$brandname;
    
  
  $query = "INSERT INTO `sms_outbox` (`id`, `message`, `datetime`, `contact_no`, `type`, `arefer`, `code`, `sent`) VALUES (NULL, '".$msg."', NULL, '".$phone."', '1', '0', NULL, '0');
 ";
$res = mysqli_query($conn,$query);
  
    send_sms_actual($phone, $msg, $debug);

    }
########################################################
# GET data from the form below
########################################################



  
        function send_sms_actual($phone, $msg, $debug=false)
    {

        global $username,$password,$smsurl,$brandname;
    
      $url  = '&sender='.$brandname;

        global $username,$password,$smsurl;
      $url  = '&username='.$username;
      $url  .= '&password='.$password;
      $url  .= '&receiver='.urlencode($phone);
      $url  .= '&sender='.$brandname;
        $url  .= '&msgdata='.urlencode($msg);
        $urltouse =  $smsurl.$url;
        // echo $urltouse; die;
        if($debug)
        {
            echo "Request: <br>$urltouse<br><br>";
        }
        //Open the URL to send the message
        $response = httpRequest($urltouse);
        if ($debug)
        {
            echo "Response: <br><pre>".
            str_replace(array("<",">"),array("<",">"),$response).
            "</pre><br>";
        }  
    
     $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $urltouse);
$content = curl_exec($ch);
    }

$debug = false;




}


function generateUniqueBarcode() {
   $min = 1000000000000000; // Minimum value for a 16-digit number
    $max = 9999999999999999; // Maximum value for a 16-digit number
    return mt_rand($min, $max);
    // return substr(str_shuffle("0123456789"), 0, 16); // Generate a random 16-digit number
}

function barcodeExists($conn, $barcode) {
    $sql = "SELECT COUNT(*) FROM `item_barcodes` WHERE `barcode` = '$barcode'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_array($result);
    return $row[0] > 0;
}



  function generateEAN($number)
{


global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;

  
  $code = str_pad($number, $info2000['barcode_limit'], '0');
  $weightflag = true;
  $sum = 0;
  // Weight for a digit in the checksum is 3, 1, 3.. starting from the last digit. 
  // loop backwards to make the loop length-agnostic. The same basic functionality 
  // will work for codes of different lengths.
  for ($i = strlen($code) - 1; $i >= 0; $i--)
  {
    $sum += (int)$code[$i] * ($weightflag?3:1);
    $weightflag = !$weightflag;
  }
  $code .= (10 - ($sum % 10)) % 10;
  return $code;
}


$current_time = date('Y-m-d H:i:s');
$current_date = date('Y-m-d');


function getPrimaryIpAddress($ipValue) {
    if ($ipValue === NULL) {
        return '';
    }

    $ipParts = explode(',', $ipValue);
    foreach ($ipParts as $ipPart) {
        $candidateIp = trim($ipPart);
        if ($candidateIp !== '') {
            return $candidateIp;
        }
    }

    return '';
}

function normalizeIpRestrictionList($ipRestriction) {
    if ($ipRestriction === NULL) {
        return '';
    }

    $normalizedIps = [];
    $ipParts = explode(',', $ipRestriction);
    foreach ($ipParts as $ipPart) {
        $candidateIp = trim($ipPart);
        if ($candidateIp === '') {
            continue;
        }
        if (!in_array($candidateIp, $normalizedIps, true)) {
            $normalizedIps[] = $candidateIp;
        }
    }

    return implode(',', $normalizedIps);
}

function isUserIpAllowed($currentIp, $ipRestriction) {
    $normalizedRestriction = normalizeIpRestrictionList($ipRestriction);
    if ($normalizedRestriction === '') {
        return true;
    }

    $normalizedCurrentIp = getPrimaryIpAddress($currentIp);
    if ($normalizedCurrentIp === '') {
        return false;
    }

    $allowedIps = explode(',', $normalizedRestriction);
    return in_array($normalizedCurrentIp, $allowedIps, true);
}

function getUserIpAddr(){
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        //ip from shared internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        //ip passed from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return getPrimaryIpAddress($ip);
}
 
function ordinal($number) {
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    if ((($number % 100) >= 11) && (($number%100) <= 13))
        return $number. 'th';
    else
        return $number. $ends[$number % 10];
}

function timeago($date) {
     $timestamp = strtotime($date); 
     
     $strTime = array("second", "minute", "hour", "day", "month", "year");
     $length = array("60","60","24","30","12","10");

     $currentTime = time();
     if($currentTime >= $timestamp) {
      $diff     = time()- $timestamp;
      for($i = 0; $diff >= $length[$i] && $i < count($length)-1; $i++) {
      $diff = $diff / $length[$i];
      }

      $diff = round($diff);
      if($strTime[$i]=='day' && $diff<10)
    { return $diff . " " . $strTime[$i] . "(s) ago "; } 
    else {  return $converted2 = date('d M Y ', strtotime($date));  }
     }
  }
  
  function numberTowords($num) {
    $ones = array(
        "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
        "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN",
        "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
    );

    $tens = array(
        "", "", "TWENTY", "THIRTY", "FORTY", "FIFTY",
        "SIXTY", "SEVENTY", "EIGHTY", "NINETY"
    );

    $levels = array(
        "", "THOUSAND", "MILLION", "BILLION", "TRILLION"
    );

    if (!is_numeric($num)) return "Invalid number";

    $num = number_format($num, 2, ".", "");
    list($whole, $decimal) = explode(".", $num);

    $whole = ltrim($whole, "0");
    if ($whole == "") $whole = "0";

    $groups = array_reverse(str_split(str_pad($whole, ceil(strlen($whole)/3)*3, "0", STR_PAD_LEFT), 3));
    $words = [];

    foreach ($groups as $i => $group) {
        $n = intval($group);
        if ($n == 0) continue;

        $h = floor($n / 100);
        $t = $n % 100;
        $line = "";

        if ($h > 0) $line .= $ones[$h] . " HUNDRED";

        if ($t > 0) {
            if ($h > 0) $line .= " ";
            if ($t < 20) {
                $line .= $ones[$t];
            } else {
                $line .= $tens[intval($t / 10)];
                if ($t % 10 > 0) $line .= " " . $ones[$t % 10];
            }
        }

        if ($line != "") {
            $words[] = $line . ($levels[$i] != "" ? " " . $levels[$i] : "");
        }
    }

    $result = implode(" ", array_reverse($words));

    if (intval($decimal) > 0) {
        $result .= " AND ";
        if ($decimal < 20) {
            $result .= $ones[intval($decimal)];
        } else {
            $result .= $tens[intval($decimal / 10)];
            if ($decimal % 10 > 0) $result .= " " . $ones[$decimal % 10];
        }
        $result .= " PAISAS";
    }

    return $result;
}

  // Basit - urdu function
function convertNumberToUrduWords($number) {
   $numbers = array(
    0 => 'صفر', 1 => 'ایک', 2 => 'دو', 3 => 'تین', 4 => 'چار',
    5 => 'پانچ', 6 => 'چھے', 7 => 'سات', 8 => 'آٹھ', 9 => 'نو',
    10 => 'دس', 11 => 'گیارہ', 12 => 'بارہ', 13 => 'تیرہ', 14 => 'چودہ',
    15 => 'پندرہ', 16 => 'سولہ', 17 => 'سترہ', 18 => 'اٹھارہ', 19 => 'انیس',
    20 => 'بیس', 21 => 'اکیس', 22 => 'بائیس', 23 => 'تئیس', 24 => 'چوبیس',
    25 => 'پچیس', 26 => 'چھببیس', 27 => 'ستائیس', 28 => 'اٹھائیس', 29 => 'انتیس',
    30 => 'تیس', 31 => 'اکتیس', 32 => 'بتیس', 33 => 'تینتیس', 34 => 'چونتیس',
    35 => 'پینتیس', 36 => 'چھتیس', 37 => 'سینتیس', 38 => 'اڑتیس', 39 => 'انتالیس',
    40 => 'چالیس', 41 => 'اکتالیس', 42 => 'بیالیس', 43 => 'تینتالیس', 44 => 'چوالیس',
    45 => 'پینتالیس', 46 => 'چھیالیس', 47 => 'سینتالیس', 48 => 'اڑتالیس', 49 => 'انچاس',
    50 => 'پچاس', 51 => 'اکیاون', 52 => 'باون', 53 => 'ترپن', 54 => 'چون',
    55 => 'پچپن', 56 => 'چھپن', 57 => 'ستاون', 58 => 'اٹھاون', 59 => 'انسٹھ',
    60 => 'ساٹھ', 61 => 'اکسٹھ', 62 => 'باسٹھ', 63 => 'تریسٹھ', 64 => 'چونسٹھ',
    65 => 'پینسٹھ', 66 => 'چھاسٹھ', 67 => 'سڑسٹھ', 68 => 'اڑسٹھ', 69 => 'انہتر',
    70 => 'ستر', 71 => 'اکہتر', 72 => 'بہتر', 73 => 'تہتر', 74 => 'چوہتر',
    75 => 'پچہتر', 76 => 'چھہتر', 77 => 'ستتر', 78 => 'اٹھتر', 79 => 'اناسی',
    80 => 'اسی', 81 => 'اکیاسی', 82 => 'بیاسی', 83 => 'تراسی', 84 => 'چوراسی',
    85 => 'پچاسی', 86 => 'چھیاسی', 87 => 'ستاسی', 88 => 'اٹھاسی', 89 => 'نواسی',
    90 => 'نوے', 91 => 'اکیانوے', 92 => 'بیانوے', 93 => 'ترانوے', 94 => 'چورانوے',
    95 => 'پچانوے', 96 => 'چھیانوے', 97 => 'ستانوے', 98 => 'اٹھانوے', 99 => 'ننانوے',
    100 => 'سو'
);



    // $numbers = array(
    //     0 => 'صفر', 1 => 'ایک', 2 => 'دو', 3 => 'تین', 4 => 'چار',
    //     5 => 'پانچ', 6 => 'چھے', 7 => 'سات', 8 => 'آٹھ', 9 => 'نو',
    //     10 => 'دس', 11 => 'گیارہ', 12 => 'بارہ', 13 => 'تیرہ', 14 => 'چودہ',
    //     15 => 'پندرہ', 16 => 'سولہ', 17 => 'سترہ', 18 => 'اٹھارہ', 19 => 'انیس',
    //     20 => 'بیس', 21 => 'اکیس', 22 => 'بائیس', 23 => 'تئیس', 24 => 'چوبیس',
    //     25 => 'پچیس', 26 => 'چھبببیس', 27 => 'ستائیس', 28 => 'اٹھائیس', 29 => 'انتیس',
    //     30 => 'تیس', 31 => 'اکتیس', 32 => 'بتیس', 33 => 'تینتیس', 34 => 'چونتس',
    //     35 => 'پینتیس', 36 => 'چھتیس', 37 => 'سینتیس', 38 => 'اٹھتیس', 39 => 'انتیس',
    //     40 => 'چالیس', 41 => 'اکتالیس', 42 => 'بیالیس', 43 => 'تینتالیس', 44 => 'چوالیس',
    //     45 => 'پینتالیس', 46 => 'چھنتالیس', 47 => 'سینتالیس', 48 => 'اڑتالیس', 49 => 'انچاس',
    //     50 => 'پچاس', 51 => 'اکتالیس', 52 => 'بیپچاس', 53 => 'تینپچاس', 54 => 'چون',
    //     55 => 'پچپن', 56 => 'چھپن', 57 => 'ستاون', 58 => 'اٹھاون', 59 => 'انسٹھ',
    //     60 => 'ساٹھ', 61 => 'اکسٹھ', 62 => 'باسٹھ', 63 => 'تریسٹھ', 64 => 'چونسٹھ',
    //     65 => 'پینسٹھ', 66 => 'چھسٹھ', 67 => 'ستاسٹھ', 68 => 'اٹھسٹھ', 69 => 'انساسٹھ',
    //     70 => 'ستر', 71 => 'اکتھر', 72 => 'بتر', 73 => 'تہتر', 74 => 'چوھتر',
    //     75 => 'پچہتر', 76 => 'چھہتر', 77 => 'ستتر', 78 => 'اٹھتر', 79 => 'انتر',
    //     80 => 'اسی', 81 => 'اکیاسی', 82 => 'بیاسی', 83 => 'تیناسی', 84 => 'چوراسی',
    //     85 => 'پچاسی', 86 => 'چھاسی', 87 => 'ستاسی', 88 => 'اٹھاسی', 89 => 'اننانوے',
    //     90 => 'نوے', 91 => 'اکیانوے', 92 => 'بیانوے', 93 => 'تینانوے', 94 => 'چورانوے',
    //     95 => 'پچانوے', 96 => 'چھانوے', 97 => 'ستانوے', 98 => 'اٹھانوے', 99 => 'نناوے',
    //     100 => 'سو'
    // );

    $hundreds = 'سو';
    $thousands = 'ہزار';
    $lakhs = 'لاکھ';
    $crores = 'کروڑ';
    $currency = 'روپیہ';
    
    if ($number < 100) {
        return $numbers[$number];
    } elseif ($number < 1000) {
        $hundreds_place = floor($number / 100);
        $remainder = $number % 100;
        return $numbers[$hundreds_place] . ' ' . $hundreds . ($remainder ? ' ' . convertNumberToUrduWords($remainder) : '');
    } elseif ($number < 100000) {
        $thousands_place = floor($number / 1000);
        $remainder = $number % 1000;
        return convertNumberToUrduWords($thousands_place) . ' ' . $thousands . ($remainder ? ' ' . convertNumberToUrduWords($remainder) : '');
    } elseif ($number < 10000000) {
        $lakhs_place = floor($number / 100000);
        $remainder = $number % 100000;
        return convertNumberToUrduWords($lakhs_place) . ' ' . $lakhs . ($remainder ? ' ' . convertNumberToUrduWords($remainder) : '');
    } else {
        $crores_place = floor($number / 10000000);
        $remainder = $number % 10000000;
        return convertNumberToUrduWords($crores_place) . ' ' . $crores . ($remainder ? ' ' . convertNumberToUrduWords($remainder) : '');
    }
}  
// function numberTowords($num){
//   $num = str_replace(array(',', ' '), '' , trim($num));
//     if(! $num) {
//         return false;
//     }
//     $num = (int) $num;
//     $words = array();
//     $list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
//         'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
//     );
//     $list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred');
//     $list3 = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion',
//         'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',
//         'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'
//     );
//     $num_length = strlen($num);
//     $levels = (int) (($num_length + 2) / 3);
//     $max_length = $levels * 3;
//     $num = substr('00' . $num, -$max_length);
//     $num_levels = str_split($num, 3);
//     for ($i = 0; $i < count($num_levels); $i++) {
//         $levels--;
//         $hundreds = (int) ($num_levels[$i] / 100);
//         $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ' ' : '');
//         $tens = (int) ($num_levels[$i] % 100);
//         $singles = '';
//         if ( $tens < 20 ) {
//             $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' );
//         } else {
//             $tens = (int)($tens / 10);
//             $tens = ' ' . $list2[$tens] . ' ';
//             $singles = (int) ($num_levels[$i] % 10);
//             $singles = ' ' . $list1[$singles] . ' ';
//         }
//         $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' );
//     } //end for loop
//     $commas = count($words);
//     if ($commas > 1) {
//         $commas = $commas - 1;
//     }
//     return implode(' ', $words);
// }

function numberTowords2($num)
{ 
$ones = array( 
1 => "one", 
2 => "two", 
3 => "three", 
4 => "four", 
5 => "five", 
6 => "six", 
7 => "seven", 
8 => "eight", 
9 => "nine", 
10 => "ten", 
11 => "eleven", 
12 => "twelve", 
13 => "thirteen", 
14 => "fourteen", 
15 => "fifteen", 
16 => "sixteen", 
17 => "seventeen", 
18 => "eighteen", 
19 => "nineteen" 
); 
$tens = array( 
1 => "ten",
2 => "twenty", 
3 => "thirty", 
4 => "forty", 
5 => "fifty", 
6 => "sixty", 
7 => "seventy", 
8 => "eighty", 
9 => "ninety" 
); 
$hundreds = array( 
"hundred", 
"thousand", 
"million", 
"billion", 
"trillion", 
"quadrillion" 
); //limit t quadrillion 
$num = number_format($num,2,".",","); 
$num_arr = explode(".",$num); 
$wholenum = $num_arr[0]; 
$decnum = $num_arr[1]; 
$whole_arr = array_reverse(explode(",",$wholenum)); 
krsort($whole_arr); 
$rettxt = ""; 
foreach($whole_arr as $key => $i){ 
if($i < 20){ 
$rettxt .= $ones[$i]; 
}elseif($i < 100){ 
$rettxt .= $tens[substr($i,0,1)]; 
$rettxt .= " ".$ones[substr($i,1,1)]; 
}else{ 
$rettxt .= $ones[substr($i,0,1)]." ".$hundreds[0]; 
$rettxt .= " ".$tens[substr($i,1,1)]; 
$rettxt .= " ".$ones[substr($i,2,1)]; 
} 
if($key > 0){ 
$rettxt .= " ".$hundreds[$key]." "; 
} 
} 
if($decnum > 0){ 
$rettxt .= " and "; 
if($decnum < 20){ 
$rettxt .= $ones[$decnum]; 
}elseif($decnum < 100){ 
$rettxt .= $tens[substr($decnum,0,1)]; 
$rettxt .= " ".$ones[substr($decnum,1,1)]; 
} 
} 
return ucwords($rettxt)." Only."; 
} 



function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);


if ($unit == "M") {
    return ($miles * 1.609344 * 1000);
  }
  else if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}


// echo itemcost('101', '1', '20', '1', '', resolve_itemcost_date());

function brandwise_enabled() {
global $info3000;
return (isset($info3000['brandwise_product']) && (int)$info3000['brandwise_product'] === 1);
}

function brandwise_normalize_id($brandInput) {
if(!brandwise_enabled()) {
  return 0;
}

if(is_array($brandInput)) {
  $brandInput = reset($brandInput);
}

$brandInput = trim((string)$brandInput);
if($brandInput === '' || strtolower($brandInput) === 'a' || strtolower($brandInput) === 'all') {
  return 0;
}

$brandId = (int)$brandInput;
if($brandId < 0) {
  $brandId = 0;
}
return $brandId;
}




function customerbookingfifoclear($item_id) {

global $conn; 
  


 $data2 = mysqli_query($conn,"Select c.id as cid from customer c, user u where u.id=c.id  && u.id='$item_id'   ") or die(mysqli_error($conn));
    
$i=1;  $dept_id=0; $company=0; $costcenter=0; 
while($info2 = mysqli_fetch_array( $data2 )) 
 { 
 
 $vendor_id=$info2['cid'];
 $tpa = $tpa2 = 0;


 $sql = "Update customer set ob=0, advance_payment='0'  where id='$vendor_id'   ";
 $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  

    $query2729=mysqli_query($conn,"SELECT SUM(oba) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];


  $query2729=mysqli_query($conn,"SELECT SUM(booking_amount+closing_charges) AS sm FROM booking where customer_id='$vendor_id' && status!=7 ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];
    
    
 $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales_debit_note where cid='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];     
        
        
  $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM sales_return where customer_id='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];     
        
        
     $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales_credit_note where cid='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];   
        
        
    
        
        
$query2729=mysqli_query($conn,"SELECT SUM(amount) AS sm FROM payment_received where cid='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];        
        
        
$query2729=mysqli_query($conn,"SELECT SUM(debit) as sm FROM `cash_transaction` where   user_id='$vendor_id' && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];   
        
        
$query2729=mysqli_query($conn,"SELECT SUM(credit) as sm FROM `cash_transaction` where   user_id='$vendor_id' && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];           





////////////////////////////////////


  $query2729=mysqli_query($conn,"SELECT SUM(ob) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];



 $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM booking where customer_id='$vendor_id' && status!=7 ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];
    


 $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM sales_debit_note where cid='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];     
        
    
     $query2729=mysqli_query($conn,"SELECT SUM(advance_payment) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 - $row['sm'];
  
  
    


if($tpa==$tpa2 ) { 




 
 
 

   
}

else if($tpa<0) 
 {
   
   
   $tpa=$tpa*(-1);
   
  $sql = "Update customer Set ob=0, advance_payment='$tpa'  where id='$vendor_id'   ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  
  $sql = "Update booking Set pending_amount=0   where customer_id='$vendor_id' && status!=7   ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  
  $sql = "Update sales_debit_note Set pending_amount=0   where cid='$vendor_id'   ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
 
 } 
 else if($tpa2>$tpa) {
    
    
    
  $customer = $vendor_id;
  $pa=$tpa2-$tpa;
  
  
  
  $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, type
FROM
(
    SELECT id, datetime, pending_amount, 1 as type FROM booking WHERE `customer_id` = '$customer' && status!=7 AND pending_amount!=0
    UNION ALL
    SELECT id, datetime, pending_amount, 2 as type FROM sales_debit_note WHERE `cid` = '$customer' AND pending_amount!=0
    
) AS UnionTable
order BY DATETIME ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id']; 
$balance= $row['pending_amount'];
$datetime= $row['datetime'];
$type= $row['type'];

$pending=$balance-$pa;
if ($pending<=0) {
 $pending=0;
}
$pa=$pa-$balance;
if($pa<=0)
$pa=0;



if ($type==1)
{


 $sql = "UPDATE booking SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}
else if ($type==2) {
    

$sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


  }

}


if($pa>=0)
{
 $sql = "UPDATE customer SET ob=0, advance_payment = '$pa' WHERE id='$customer'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

} 
    
else {
    
    
    
    
    $cid=$vendor_id;
    $pa=$tpa-$tpa2;
    

$result = mysqli_query($conn,"SELECT id, datetime, pending_amount, total, type
FROM
(
    SELECT id, datetime, pending_amount, total, 1 as type FROM booking WHERE`customer_id` = '$cid' && status!=7 AND pending_amount!=total && id IN (Select invoice_id from payment_record where payment_id='$deptid' && clear_type='1') 
    UNION ALL
    SELECT id, datetime, pending_amount, total, 2 as type FROM sales_debit_note WHERE `cid` = '$cid' AND pending_amount!=total
    
) AS UnionTable
order BY DATETIME Desc ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id']; 
$balance= $row['pending_amount'];
$max= $row['total'];
$datetime= $row['datetime'];
$type= $row['type'];


$pending=$balance+$pa;


if ($pending>=$max) {
 $pending=$max;
}

$remainpa=$pending-$balance;


$pa= $pa-$remainpa;

if($pa<=0)
$pa=0;


if ($type==1)
{



$sql = "UPDATE booking SET pending_amount = pending_amount + '$old_payment' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));




}
elseif ($type==2) {
    

$sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


  }


}



if($pa>=0)
{
 $sql = "UPDATE customer SET ob = '$pa', advance_payment = 0 WHERE id='$cid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

      
   
   
   
   }


 }


 
  


}



function customerpaymentfifoclearsnd($item_id) {


global $conn; 
  



$vendor_id=$item_id;
 $tpa = 0;

	  $query2729=mysqli_query($conn,"SELECT SUM(oba) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
		
		$row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];


  $query2729=mysqli_query($conn,"SELECT SUM(total2) AS sm FROM so where customer_id='$vendor_id' AND order_delete=0  AND execute_complete=1 ") or die(mysqli_error($conn));
		
		$row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];
		
		
		
        
        
  $query2729=mysqli_query($conn,"SELECT SUM(total2) AS sm FROM so_return where customer_id='$vendor_id' AND order_delete=0  AND execute_complete=1 ") or die(mysqli_error($conn));
		
		$row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];     
        
        
     
         
        
$query2729=mysqli_query($conn,"SELECT SUM(amount) AS sm FROM payment_received where cid='$vendor_id' AND order_delete=0  AND execute_complete=1 ") or die(mysqli_error($conn));
		
		$row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];        


        
	 
 if($tpa<=0) 
 {
	
	 
	 $tpa=$tpa*(-1);
	 
  $sql = "Update customer Set ob=0, advance_payment='$tpa'  where id='$vendor_id'   ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  
  $sql = "Update so Set amount_received=total2   where customer_id='$vendor_id' AND order_delete=0  AND execute_complete=1   ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
 
  
 
 } 
 else {
	 
	 
	 
	 
	 $sql = "UPDATE customer SET advance_payment = '0', ob = '0' WHERE id='$vendor_id'" ;
     $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn)) ;
	 
	 
	 	 $sql = "UPDATE so SET amount_received=total2  WHERE customer_id='$vendor_id' AND order_delete=0  AND execute_complete=1" ;
     $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn)) ;
	 
	 
	 
	  $query2729=mysqli_query($conn,"SELECT SUM(ob) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
		
		$row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];


  $query2729=mysqli_query($conn,"SELECT SUM(total2-amount_received) AS sm FROM so where customer_id='$vendor_id'  AND order_delete=0  AND execute_complete=1 ") or die(mysqli_error($conn));
		
		$row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];
		
		
		
		
		
		

		$pa = $tpa-$tpa2;	
		
		
		
		
		$customer = $vendor_id;	
		$cid = $vendor_id;	
		
		
$result2 = mysqli_query($conn,"SELECT advance_payment FROM `customer` WHERE `id` = '$cid' ") or die(mysqli_error($conn));
$row2 = mysqli_fetch_array($result2);

$adv_pay = $row2['advance_payment'];

if($adv_pay>0){

$pending=$adv_pay-$pa;

if ($pending<=0)
$pending=0;

$pa=$pa-$adv_pay;

if($pa<=0)
$pa=0;


$sql = "UPDATE customer SET advance_payment = '$pending' WHERE id='$cid'";
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}



if($pa>0)
{

$result = mysqli_query($conn,"SELECT id, datetime, pending_amount, total, type
FROM
(
    SELECT id, datetime, total2-amount_received as pending_amount, total2 as total, 1 as type FROM so WHERE`customer_id` = '$cid' AND order_delete=0  AND execute_complete=1 AND amount_received!=0
    
    
) AS UnionTable
order BY DATETIME Desc ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id'];	
$balance= $row['pending_amount'];
$max= $row['total'];
$datetime= $row['datetime'];
$type= $row['type'];


$pending=$balance+$pa;


if ($pending>=$max) {
 $pending=$max;
}


$rec = $max-$pending;


$remainpa=$pending-$balance;


$pa= $pa-$remainpa;

if($pa<=0)
$pa=0;


if ($type==1)
{


$sql = "UPDATE so SET amount_received = '$rec' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}
elseif ($type==2) {
		

$sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


	}


}
}

if($pa>0)
{
$result = mysqli_query($conn,"SELECT ob, oba FROM `customer` WHERE `id` = '$cid' AND ob!=oba AND oba!=0 ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{	
$balance= $row['ob'];
$max= $row['oba'];
$pending=$balance+$pa;

if($pending>=$max)
$pending=$max;


$sql = "UPDATE customer SET ob = '$pending' WHERE id='$cid'" ;
 $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}
}



}


}






function customerpaymentfifoclear($item_id, $brand_id = 0) {


global $conn, $info3000; 

$brandMode = isset($info3000['brandwise_product']) ? (int)$info3000['brandwise_product'] : 0;
$brand_id = (int)$brand_id;
$brandScoped = ($brandMode === 1 && $brand_id > 0);
$brandFilter = $brandScoped ? " AND brand_id='$brand_id' " : "";
  


 $data2 = mysqli_query($conn,"Select c.id as cid from customer c, user u where u.id=c.id  && u.id='$item_id'   ") or die(mysqli_error($conn));
    
$i=1;  $dept_id=0; $company=0; $costcenter=0; 
while($info2 = mysqli_fetch_array( $data2 )) 
 { 
 
 $vendor_id=$info2['cid'];
 $tpa = $tpa2 = 0;


 $sql = "Update customer set ob=0, advance_payment='0'  where id='$vendor_id'   ";
 $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  

    if(!$brandScoped) {
      $query2729=mysqli_query($conn,"SELECT SUM(oba) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
      $row = mysqli_fetch_array($query2729);
      $tpa = $tpa + $row['sm'];
    }


  $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales where customer_id='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];
    
    
 $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales_debit_note where cid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];     
        
        
  $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM sales_return where customer_id='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];     
        
        
     $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales_credit_note where cid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];   
        
        
    
        
        
$query2729=mysqli_query($conn,"SELECT SUM(amount) AS sm FROM payment_received where cid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];        
        
        
$query2729=mysqli_query($conn,"SELECT SUM(debit) as sm FROM `cash_transaction` where   user_id='$vendor_id' $brandFilter && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];   
        
        
$query2729=mysqli_query($conn,"SELECT SUM(credit) as sm FROM `cash_transaction` where   user_id='$vendor_id' $brandFilter && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];           





////////////////////////////////////


  if(!$brandScoped) {
    $query2729=mysqli_query($conn,"SELECT SUM(ob) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa2 = $tpa2 + $row['sm'];
  }



 $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM sales where customer_id='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];
    


 $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM sales_debit_note where cid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];     
        
    
     if(!$brandScoped) {
        $query2729=mysqli_query($conn,"SELECT SUM(advance_payment) AS sm FROM customer where id='$vendor_id' ") or die(mysqli_error($conn));
        $row = mysqli_fetch_array($query2729);
        $tpa2 = $tpa2 - $row['sm'];
     }
  
  
    


if($tpa==$tpa2 ) { 




 
 
 

   
}

else if($tpa<0) 
 {
   
   
   $tpa=$tpa*(-1);
   
  if(!$brandScoped) {
      $sql = "Update customer Set ob=0, advance_payment='$tpa'  where id='$vendor_id'   ";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
  
  
  $sql = "Update sales Set pending_amount=0   where customer_id='$vendor_id' $brandFilter ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  
  $sql = "Update sales_debit_note Set pending_amount=0   where cid='$vendor_id' $brandFilter ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
 
 } 
 else if($tpa2>$tpa) {
    
    
    
  $customer = $vendor_id;
  $pa=$tpa2-$tpa;
  
  
  
  $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, type
FROM
(
    SELECT id, datetime, pending_amount, 1 as type FROM sales WHERE `customer_id` = '$customer' $brandFilter AND pending_amount!=0
    UNION ALL
    SELECT id, datetime, pending_amount, 2 as type FROM sales_debit_note WHERE `cid` = '$customer' $brandFilter AND pending_amount!=0
    
) AS UnionTable
order BY DATETIME ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id']; 
$balance= $row['pending_amount'];
$datetime= $row['datetime'];
$type= $row['type'];

$pending=$balance-$pa;
if ($pending<=0) {
 $pending=0;
}
$pa=$pa-$balance;
if($pa<=0)
$pa=0;



if ($type==1)
{


 $sql = "UPDATE sales SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}
else if ($type==2) {
    

$sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


  }

}


if($pa>=0 && !$brandScoped)
{
 $sql = "UPDATE customer SET ob=0, advance_payment = '$pa' WHERE id='$customer'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

} 
    
else {
    
    
    
    
    $cid=$vendor_id;
    $pa=$tpa-$tpa2;
    

$result = mysqli_query($conn,"SELECT id, datetime, pending_amount, total, type
FROM
(
    SELECT id, datetime, pending_amount, total, 1 as type FROM sales WHERE`customer_id` = '$cid' $brandFilter AND pending_amount!=total  
    UNION ALL
    SELECT id, datetime, pending_amount, total, 2 as type FROM sales_debit_note WHERE `cid` = '$cid' $brandFilter AND pending_amount!=total
    
) AS UnionTable
order BY DATETIME Desc ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id']; 
$balance= $row['pending_amount'];
$max= $row['total'];
$datetime= $row['datetime'];
$type= $row['type'];


$pending=$balance+$pa;


if ($pending>=$max) {
 $pending=$max;
}

$remainpa=$pending-$balance;


$pa= $pa-$remainpa;

if($pa<=0)
$pa=0;


if ($type==1)
{



$sql = "UPDATE sales SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));




}
elseif ($type==2) {
    

$sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


  }


}



if($pa>=0 && !$brandScoped)
{
 $sql = "UPDATE customer SET ob = '$pa', advance_payment = 0 WHERE id='$cid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

      
   
   
   
   }


 }


 
  


}




function supplierpaymentfifoclear($item_id, $brand_id = 0) {

global $conn, $info3000; 

$brandMode = isset($info3000['brandwise_product']) ? (int)$info3000['brandwise_product'] : 0;
$brand_id = (int)$brand_id;
$brandScoped = ($brandMode === 1 && $brand_id > 0);
$brandFilter = $brandScoped ? " AND brand_id='$brand_id' " : "";






 $data2 = mysqli_query($conn,"Select c.id as cid from vendor c, user u where u.id=c.id  && u.id='$item_id'    ") or die(mysqli_error($conn));
    
$i=1;  $dept_id=0; $company=0; $costcenter=0; 
while($info2 = mysqli_fetch_array( $data2 )) 
 { 
 
 $vendor_id=$info2['cid'];
 $tpa = $tpa2 = 0;


 if(!$brandScoped) {
 $sql = "Update vendor set ob=0, advance_payment='0'  where id='$vendor_id'   ";
 $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
 }
  
  

    if(!$brandScoped) {
        $query2729=mysqli_query($conn,"SELECT SUM(oba) AS sm FROM vendor where id='$vendor_id' ") or die(mysqli_error($conn));
        $row = mysqli_fetch_array($query2729);
        $tpa = $tpa + $row['sm'];
    }


  $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM purchasing where vendor_id='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];
    
    
 $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM purchase_credit_note where vid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];     
        
        
  $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM purchase_returns where vendor_id='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];     
        
        
     $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM purchase_debit_note where vid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];   
        
        
    
        
        
$query2729=mysqli_query($conn,"SELECT SUM(amount) AS sm FROM payment_sent where vid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];        
        
        
$query2729=mysqli_query($conn,"SELECT SUM(credit) as sm FROM `cash_transaction` where   user_id='$vendor_id' $brandFilter && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa + $row['sm'];   
        
        
$query2729=mysqli_query($conn,"SELECT SUM(debit) as sm FROM `cash_transaction` where   user_id='$vendor_id' $brandFilter && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa = $tpa - $row['sm'];           





////////////////////////////////////


  if(!$brandScoped) {
    $query2729=mysqli_query($conn,"SELECT SUM(ob) AS sm FROM vendor where id='$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa2 = $tpa2 + $row['sm'];
  }



 $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM purchasing where vendor_id='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];
    


 $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM purchase_credit_note where vid='$vendor_id' $brandFilter ") or die(mysqli_error($conn));
    
    $row = mysqli_fetch_array($query2729);

        $tpa2 = $tpa2 + $row['sm'];     
        
    
     if(!$brandScoped) {
        $query2729=mysqli_query($conn,"SELECT SUM(advance_payment) AS sm FROM vendor where id='$vendor_id' ") or die(mysqli_error($conn));
        $row = mysqli_fetch_array($query2729);
        $tpa2 = $tpa2 - $row['sm'];
     }
  
  
    


if($tpa==$tpa2 ) { 




 
 
 

   
}

else if($tpa<0) 
 {
   
   
   $tpa=$tpa*(-1);
   
  if(!$brandScoped) {
      $sql = "Update vendor Set ob=0, advance_payment='$tpa'  where id='$vendor_id'   ";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  }
  
  
  $sql = "Update purchasing Set pending_amount=0   where vendor_id='$vendor_id' $brandFilter ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
  
  $sql = "Update purchase_credit_note Set pending_amount=0   where vid='$vendor_id' $brandFilter ";
  $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
  
 
 } 
 else if($tpa2>$tpa) {
    
    
    
  $customer = $vendor_id;
  $pa=$tpa2-$tpa;
  
  
  
  $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, type
FROM
(
    SELECT id, datetime, pending_amount, 1 as type FROM purchasing WHERE `vendor_id` = '$customer' $brandFilter AND pending_amount!=0
    UNION ALL
    SELECT id, datetime, pending_amount, 2 as type FROM purchase_credit_note WHERE `vid` = '$customer' $brandFilter AND pending_amount!=0
    
) AS UnionTable
order BY DATETIME ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id']; 
$balance= $row['pending_amount'];
$datetime= $row['datetime'];
$type= $row['type'];

$pending=$balance-$pa;
if ($pending<=0) {
 $pending=0;
}
$pa=$pa-$balance;
if($pa<=0)
$pa=0;



if ($type==1)
{


 $sql = "UPDATE purchasing SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


}
else if ($type==2) {
    

$sql = "UPDATE purchase_credit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


  }

}


if($pa>=0 && !$brandScoped)
{
 $sql = "UPDATE vendor SET ob=0, advance_payment = '$pa' WHERE id='$customer'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

}

} 
    
else {
    
    
    
    
    $cid=$vendor_id;
    $pa=$tpa-$tpa2;
    

$result = mysqli_query($conn,"SELECT id, datetime, pending_amount, total, type
FROM
(
    SELECT id, datetime, pending_amount, total_amount as total, 1 as type FROM purchasing WHERE `vendor_id` = '$cid' $brandFilter AND pending_amount!=total_amount
    UNION ALL
    SELECT id, datetime, pending_amount, total, 2 as type FROM purchase_credit_note WHERE `vid` = '$cid' $brandFilter AND pending_amount!=total
    
) AS UnionTable
order BY DATETIME Desc ") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$pid= $row['id']; 
$balance= $row['pending_amount'];
$max= $row['total'];
$datetime= $row['datetime'];
$type= $row['type'];


$pending=$balance+$pa;


if ($pending>=$max) {
 $pending=$max;
}

$remainpa=$pending-$balance;


$pa= $pa-$remainpa;

if($pa<=0)
$pa=0;


if ($type==1)
{



$sql = "UPDATE purchasing SET pending_amount = pending_amount + '$old_payment' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));




}
elseif ($type==2) {
    

$sql = "UPDATE purchase_credit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));


  }


}



if($pa>=0 && !$brandScoped)
{
 $sql = "UPDATE vendor SET ob = '$pa', advance_payment = 0 WHERE id='$cid'" ;
$retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
}

      
   
   
   
   }


 }


 
  


}



function itemwithnocost($item_id, $item_type, $item_qty, $item_warehouse, $item_subwarehouse  ) {

global $conn; 

 $returncost=0;

$rate_incarton =  mysqli_get_var("Select rate_incarton from main  "); 

if($rate_incarton==0) { $packing=1; } else {
  
  if($item_type==0) $aa = ' inventory '; else if($item_type==1) $aa = ' component '; else $aa = ' assets ';
  
$packing =  mysqli_get_var("Select packing from $aa where id='$item_id'  "); 

  
  }
 
$costing_type =  mysqli_get_var("Select nocosting_sequence1 from main3  "); 
 
 
 
if($costing_type==7) {  $returncost =  mysqli_get_var("SELECT item_cost  FROM warehouse_transaction WHERE item_id='$item_id' && type_component='$item_type' && item_cost!=0 && deleted=0 order by id DESC Limit 1  ");  }
 else if($costing_type==3) {  $returncost =  mysqli_get_var("Select tp from purchasing_details where prd_id='$item_id' && order_id IN (SELECT id FROM purchasing WHERE type_component='$item_type')  ");
 
 $returncost = $returncost/$packing;
 
   }
 else  if($costing_type==6) {  $returncost =  mysqli_get_var("Select tp from sales_details where prd_id='$item_id' && order_id IN (SELECT id FROM sales WHERE type_component='$item_type')   "); 
 
$returncost = $returncost/$packing; 
  }
 else  {  if($item_type==0) $aa = ' inventory '; else if($item_type==1) $aa = ' component '; else $aa = ' assets ';   $returncost =  mysqli_get_var("Select unit_cost from $aa where id='$item_id'  ");  }


if($returncost=='') {

$costing_type =  mysqli_get_var("Select nocosting_sequence2 from main3  "); 


if($costing_type==7) {  $returncost =  mysqli_get_var("SELECT item_cost  FROM warehouse_transaction WHERE item_id='$item_id' && type_component='$item_type' && item_cost!=0 && deleted=0 order by id DESC Limit 1  ");  }
 else  if($costing_type==3) {  $returncost =  mysqli_get_var("Select tp from purchasing_details where prd_id='$item_id' && order_id IN (SELECT id FROM purchasing WHERE type_component='$item_type')  "); 
 
$returncost = $returncost/$packing; 
  }
 else  if($costing_type==6) {  $returncost =  mysqli_get_var("Select tp from sales_details where prd_id='$item_id' && order_id IN (SELECT id FROM sales WHERE type_component='$item_type')  "); 
 
 $returncost = $returncost/$packing;
  }
 else  {  if($item_type==0) $aa = ' inventory '; else if($item_type==1) $aa = ' component '; else $aa = ' assets ';   $returncost =  mysqli_get_var("Select unit_cost from $aa where id='$item_id'  ");  }


}




if($returncost=='') {

$costing_type =  mysqli_get_var("Select nocosting_sequence3 from main3  "); 


if($costing_type==7) {  $returncost =  mysqli_get_var("SELECT item_cost  FROM warehouse_transaction WHERE item_id='$item_id' && type_component='$item_type' && item_cost!=0 && deleted=0 order by id DESC Limit 1  ");  }
 else  if($costing_type==3) {  $returncost =  mysqli_get_var("Select tp from purchasing_details where prd_id='$item_id' && order_id IN (SELECT id FROM purchasing WHERE type_component='$item_type')  "); 
 
 $returncost = $returncost/$packing;
 
  }
 else  if($costing_type==6) {  $returncost =  mysqli_get_var("Select tp from sales_details where prd_id='$item_id' && order_id IN (SELECT id FROM sales WHERE type_component='$item_type' )  "); 
 
 $returncost = $returncost/$packing;
 
  }
 else  {  if($item_type==0) $aa = ' inventory '; else if($item_type==1) $aa = ' component '; else $aa = ' assets ';   $returncost =  mysqli_get_var("Select unit_cost from $aa where id='$item_id'  ");  }



}



  
   if($returncost == ''){ $returncost = 0; } 

    
if(is_numeric($returncost) && $returncost!='' && $returncost!=0 && $item_qty!=0 ) { $returncost = $returncost/$item_qty; }    
  
  if(is_numeric($returncost) && $returncost!='' && $returncost!='NAN') {  } else { $returncost=0; }
 
  if(is_nan($returncost)) { $returncost=0; }
  
  
  $maxx = strlen(strrchr($returncost, '.')); // 3
  
  if($maxx>4) {
    
 $returncost = number_format((float)$returncost, 4, '.', '');
    
    }
  
  return $returncost;
  




}


function get_itemcost_fallback_unit($item_id, $item_type, $wt_id){
global $conn;   

if($wt_id==0) $wt_id2 = " && 1=1 "; else $wt_id2= " && id < '$wt_id' ";

$rate_incarton = mysqli_get_var("Select rate_incarton from main  ");
if($rate_incarton == 0){
  $packing = 1;
} else {
  if($item_type==0) {
    $aa = ' inventory ';
  } elseif($item_type==1) {
    $aa = ' component ';
  } else {
    $aa = ' assets ';
  }
  $packing = mysqli_get_var("Select packing from $aa where id='$item_id'  ");
  if($packing == '' || $packing == 0){
    $packing = 1;
  }
}


  $returncost = null;

    $returncost = mysqli_get_var("SELECT item_cost FROM warehouse_transaction WHERE item_id='$item_id' $wt_id2 && type_component='$item_type' && item_cost!=0 && deleted=0 order by id DESC Limit 1  ");
if($returncost == '')
{
$returncost = 0;
}   

  if($returncost !== null && $returncost !== '' && is_numeric($returncost) && !is_nan($returncost)){
    $returncost = (float)$returncost;
   
  }


return $returncost;
}

function itemcost_lookup_last_cost($item_id, $item_type, $datefilterCondition = '', $warehouseId = null, $subWarehouseId = null, $wt_id = 0){
    global $conn, $info2000;

    $costByWarehouse = isset($info2000['costing_by_warehouse']) ? (int)$info2000['costing_by_warehouse'] : 1;
    $enforceWarehouse = ($costByWarehouse !== 0);

    $itemId = (int)$item_id;
    $itemType = (int)$item_type;
    $conditions = [
        "w.item_id='$itemId'",
        "w.type_component='$itemType'",
        "w.deleted=0",
        "w.item_cost>0",
        "w.id<'$wt_id'"
    ];

    if($enforceWarehouse && $warehouseId !== null && $warehouseId !== '' && $warehouseId !== '0'){
        $conditions[] = "w.warehouse_id='".(int)$warehouseId."'";
    }

    if($enforceWarehouse && $subWarehouseId !== null && $subWarehouseId !== '' && $subWarehouseId !== '0'){
        $conditions[] = "w.subwarehouse_id='".(int)$subWarehouseId."'";
    }

    $dateCondition = trim((string)$datefilterCondition);
    if($dateCondition !== ''){
        if(strpos($dateCondition, '&&') === 0){
            $dateCondition = trim(substr($dateCondition, 2));
        } elseif(stripos($dateCondition, 'AND') === 0){
            $dateCondition = trim(substr($dateCondition, 3));
        }
        if($dateCondition !== ''){
            $conditions[] = $dateCondition;
        }
    }
// echo "SELECT w.item_cost FROM warehouse_transaction w WHERE ".implode(' AND ', $conditions)." ORDER BY w.datetime DESC, w.id DESC LIMIT 1";die;
    $sql = "SELECT w.item_cost FROM warehouse_transaction w WHERE ".implode(' AND ', $conditions)." ORDER BY w.datetime DESC, w.id DESC LIMIT 1";
    $value = mysqli_get_var($sql);
    if($value === null || $value === ''){
        return null;
    }

    return (float)$value;
}

function resolve_itemcost_date($input = null){
global $conn, $current_date;

    $candidate = $input;

    if(is_array($candidate)){
        $candidate = array_filter($candidate, function($value){
            return $value !== null && $value !== '';
        });
        if(!empty($candidate)){
            $candidate = reset($candidate);
        } else {
            $candidate = null;
        }
    }

    if($candidate === null || $candidate === ''){
        $sources = [];
        if(isset($_POST) && is_array($_POST)){
            $sources[] = $_POST;
        }
        if(isset($_REQUEST) && is_array($_REQUEST)){
            $sources[] = $_REQUEST;
        }
        $keys = ['datetime','date','voucher_date','invoice_date','posting_date','entry_date','document_date','stock_date','transaction_date','opening_date','closing_date'];
        foreach($sources as $source){
            foreach($keys as $key){
                if(isset($source[$key]) && $source[$key] !== ''){
                    if(is_array($source[$key])){
                        foreach($source[$key] as $value){
                            if($value !== null && $value !== ''){
                                $candidate = $value;
                                break 3;
                            }
                        }
                    } else {
                        $candidate = $source[$key];
                        break 2;
                    }
                }
            }
        }
    }

    if($candidate === null || $candidate === ''){
        if(isset($current_date) && $current_date !== ''){
            $candidate = $current_date;
        } else {
            return null;
        }
    }

    $timestamp = strtotime($candidate);
    if($timestamp === false){
        return null;
    }

    return date('Y-m-d H:i:s', $timestamp);
}


function itemcost($item_id, $item_type, $item_qty, $item_warehouse, $item_subwarehouse, $datefilter=null, $batch=null, $wt_id=0  ) {

 global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;

$returncost=0;


if($wt_id==0) $wt_id2 = " && 1=1 "; else $wt_id2= " && w.id < '$wt_id' ";

if($batch=='') $batch = " && 1=1 "; else $batch= " && w.batch_no='$batch' ";

if($department_id=='' || $department_id==0) $department_id2 = ""; else $department_id2= " && w.department_id='$department_id' ";

if($info2000['costing_by_warehouse']==1) {

if($item_warehouse=='') $item_warehouse2 = " "; else $item_warehouse2= " && w.warehouse_id='$item_warehouse' ";
}
if($item_subwarehouse=='') $item_subwarehouse = ""; else $item_subwarehouse= " && w.subwarehouse_id='$item_subwarehouse' ";

$ii = 0;

$datefilter2 = '';
if($datefilter!='')  {
    $datefilter2 = " AND DATE(w.datetime) <= DATE('$datefilter') ";
}
$fallbackDateFilter2 = '';
if($datefilter!='')  {
    $fallbackDateFilter2 = " AND DATE(w.datetime) <= DATE(DATE_SUB('$datefilter', INTERVAL 1 DAY)) ";
}

$iit = $item_id;
$iit_type = $item_type;

 if($item_id=='') { 
        $item_id = ""; 
        $item_id2 = 0; 
    } else { 
        $item_id2 = $item_id; 
        $item_id = " && w.item_id='$item_id' ";  
    }

    if($item_type=='') 
        $item_type = " && w.type_component='0' "; 
    else 
        $item_type = " && w.type_component='$item_type' ";

   




// Costing Type 1:  0 value 
// Costing Type 2: Last warehouse_transaction unit cost
// Costing Type 3: Last Purchase price 
// Costing Type 4: Weighted average 
// Costing Type 5: Unit cost from master table
// Costing Type 6: Sales price from sales
// Costing Type 7: Last warehouse_transaction unit cost
// Costing Type 8: batch wise weighted avg


// If cost comes in negative last cost from warehouse_transaction 

$costing_type =  mysqli_get_var("Select costing_type from main2  "); 

$item_id2 = $item_id;

$item_type2 = $item_type;


if($costing_type==1) 
{

$returncost = 0;

}

 else if($costing_type==8) 
{

$item_qty2 = 0;

$meanvalue  = 0;

$meanvalue2 = 0;



$aqtycost_old = mysqli_get_var("SELECT SUM(w.item_cost*w.qty) as cb FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1   $item_id  $batch  $datefilter2 && w.deleted=0 order by w.id DESC  ");

$aqtycost_forqty = mysqli_get_var("SELECT SUM(w.qty) as cb FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1   $item_id  $batch  $datefilter2 && w.deleted=0 order by w.id DESC   ");

$aqtycost = 0;
if($aqtycost_forqty > 0) {
    $aqtycost = $aqtycost_old / $aqtycost_forqty;
}

if($aqtycost == '')
{
    $aqtycost = 0;
}
if (!is_finite($aqtycost) || is_nan($aqtycost)) 
{
    $aqtycost = 0;
}
  $returncost = $aqtycost; 
  
  
  if($returncost == 0)
      $returncost = 0;
  
$returncost = $aqtycost * $item_qty;

if($returncost <= 0) {
    $last_cost = itemcost_lookup_last_cost($iit, $iit_type, $fallbackDateFilter2, $warehouseIdValue, $subWarehouseIdValue);
    if($last_cost === null || $last_cost <= 0) {
        $last_cost = get_itemcost_fallback_unit($iit, $iit_type);
    }
    if($last_cost > 0) {
        $returncost = $last_cost * $item_qty;
    }
}
// $returncost = $aqtycost_old;

//   if($returncost == 0){
     
//       $returncost = mysqli_get_var("SELECT unit_cost FROM inventory WHERE id = '$item_id2' ");
//       $returncost = $returncost*$item_qty;
  
//   }
  

}

else if($costing_type==5) 
{ 

if($item_type==0) 
{
  
$returncost =  mysqli_get_var("Select unit_cost from inventory where id='$item_id'  "); 

} if($item_type==2) 
{
  
$returncost =  mysqli_get_var("Select unit_cost from assets where id='$item_id'  "); 

} else {
  
$returncost =  mysqli_get_var("Select unit_cost from component where id='$item_id'  "); 
  
  }
  

$returncost = $returncost*$item_qty;  

}


 else if($costing_type==4) 
{
    $item_qty2 = 0;
    $meanvalue  = 0;
    $meanvalue2 = 0;


    $aqtycost = mysqli_get_var("SELECT SUM(w.item_cost*w.qty) as cb 
                                FROM warehouse_transaction w, warehouse_transaction_type t 
                                WHERE w.tran_type=t.id && t.type=1 && item_cost!=0 
                                $item_subwarehouse $item_warehouse2 $department_id2 $item_id $item_type $datefilter2 $wt_id2 
                                && w.deleted=0");

    $vqtycost = mysqli_get_var("SELECT SUM(w.item_cost*w.qty) as cb 
                                FROM warehouse_transaction w, warehouse_transaction_type t 
                                WHERE w.tran_type=t.id && t.type=0 && item_cost!=0 
                                $item_subwarehouse $item_warehouse2 $department_id2 $item_id $item_type $datefilter2 $wt_id2 
                                && w.deleted=0");

    $bcost = $aqtycost - $vqtycost;  

    $plus_qty = mysqli_get_var("SELECT SUM(w.qty) as cb 
                                FROM warehouse_transaction w, warehouse_transaction_type t 
                                WHERE w.tran_type=t.id && t.type=1 && item_cost!=0 
                                $item_subwarehouse $item_warehouse2 $department_id2 $item_id $item_type $datefilter2 $wt_id2 
                                && w.deleted=0");

    $negative_qty = mysqli_get_var("SELECT SUM(w.qty) as cb 
                                    FROM warehouse_transaction w, warehouse_transaction_type t 
                                    WHERE w.tran_type=t.id && t.type=0 && item_cost!=0 
                                    $item_subwarehouse $item_warehouse2 $department_id2 $item_id $item_type $datefilter2 $wt_id2 
                                    && w.deleted=0");

    $plusminus_qty = $plus_qty - $negative_qty;

    if($plusminus_qty > 0) {
        $returncost = ($bcost / $plusminus_qty) * $item_qty;
    } else {
        $returncost = 0;
    }

    if($plusminus_qty <= 0 || $returncost <= 0) {
        $last_cost = itemcost_lookup_last_cost($iit, $iit_type, $fallbackDateFilter2, $warehouseIdValue, $subWarehouseIdValue, $wt_id);
        if($last_cost === null || $last_cost <= 0) {
            $last_cost = get_itemcost_fallback_unit($iit, $iit_type, $wt_id);
        }
        if($last_cost > 0) {
            $returncost = $last_cost * $item_qty;
        }
    }


    
}

 else if($costing_type==2) 
{
  
$item_qty2 = 0;

$meanvalue  = 0;

$meanvalue2 = 0;


$ii = 0;

$data3 = mysqli_query($conn,"SELECT item_cost, qty, type, datetime FROM ( SELECT w.item_cost, w.qty, t.type, w.datetime FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=0 && item_cost!=0 $item_subwarehouse $item_warehouse $department_id2 $item_id $item_type $datefilter2 && w.deleted=0  && w.warehouse_id!=0 && w.warehouse_id!=0 UNION ALL SELECT w.item_cost, w.qty, t.type, w.datetime FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1 && item_cost!=0 $item_subwarehouse $department_id2  $item_warehouse $item_id $item_type $datefilter2 && w.deleted=0  && w.warehouse_id!=0 && w.warehouse_id!=0 ) AS bb order by datetime ASC  ") or die(mysqli_error($conn)); 

 while($info3 = mysqli_fetch_array( $data3 )) 
 { 
 
 $qty5 = $info3['qty'];
 $type5 = $info3['type'];
 
 
 $ii++;
 
 if($type5==0) $nn=$ii;
   
 
 }

$iii = 0;

$data4 = mysqli_query($conn,"SELECT item_cost, qty, type, datetime FROM ( SELECT w.item_cost, w.qty, t.type, w.datetime FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=0 && item_cost!=0 $item_subwarehouse $item_warehouse $department_id2 $item_id $item_type $datefilter2 && w.deleted=0  && w.warehouse_id!=0 && w.warehouse_id!=0 UNION ALL SELECT w.item_cost, w.qty, t.type, w.datetime FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1 && item_cost!=0 $item_subwarehouse $department_id2  $item_warehouse $item_id $item_type $datefilter2 && w.deleted=0  && w.warehouse_id!=0 && w.warehouse_id!=0 ) AS bb order by datetime ASC  ") or die(mysqli_error($conn)); 

 while($info4 = mysqli_fetch_array( $data4 )) 
 { 
 
 $type = $info4['type'];
 if($type==1) {   $qty = $info4['qty']; } else {  $qty = -1*$info4['qty']; }
  
  
$iii++;


  $item_qty2 = $item_qty2 +  $qty; 

   
   $less = 0;
   
   
      if($item_qty2>=$item_qty && $iii>=$nn ) { $less = $item_qty2-$item_qty; } else { $less=0; } 
  
  $qty = $qty - $less;
  
 
  $item_cost = $info4['item_cost']*$qty;

   

  
   
  $meanvalue = $meanvalue + $item_cost;
 
  $meanvalue2 = $meanvalue2 + $qty;
  
  
  
    $item_cost2 = $meanvalue / $meanvalue2;
 

 
 
  
  if($item_qty2>=$item_qty && $iii>=$nn) { break; } 
  
 
 
 }

   $bb =  $item_cost2*$item_qty;
  
  if($bb=='') $bb=0;
  
  $returncost = $bb;
  
  
} else if($costing_type == 3){
  $returncost = mysqli_get_var("SELECT d.tp FROM purchasing_details AS d JOIN purchasing AS p WHERE p.id = d.order_id AND d.prd_id = '$item_id' AND p.type_component = '$item_type' ORDER BY d.id DESC LIMIT 1 ");
  if($returncost == ''){
    if($item_type==0) {
      $returncost =  mysqli_get_var("Select unit_cost from inventory where id='$item_id'  "); 
    }else if($item_type==2) {
      $returncost =  mysqli_get_var("Select unit_cost from assets where id='$item_id'  "); 
    } else {
      $returncost =  mysqli_get_var("Select unit_cost from component where id='$item_id'  "); 
    }
  }
   $returncost = $returncost*$item_qty;
}



  
  if($returncost <= 0 || $returncost == '' ) {
    $last_cost = itemcost_lookup_last_cost($iit, $iit_type, $fallbackDateFilter2, $warehouseIdValue, $subWarehouseIdValue, $wt_id);
    if($last_cost === null || $last_cost <= 0) {
        $last_cost = get_itemcost_fallback_unit($iit, $iit_type, $wt_id);
    }
    if($last_cost > 0) {
        $returncost = $last_cost * $item_qty;
    } else {
        $returncost = 0;
    }
  }
    
   
    if($returncost == ''){ $returncost = 0; } 

    
if(is_numeric($returncost) && $returncost!='' && $returncost!=0 && $item_qty!=0 ) { $returncost = $returncost/$item_qty; }    
  
  if(is_numeric($returncost) && $returncost!='' && $returncost!='NAN') {  } else { $returncost=0; }
 
  if(is_nan($returncost)) { $returncost=0; }
  
  
  
$maxx = strlen(strrchr($returncost, '.')); // 3
  
  if($maxx>4) {
    
 $returncost = number_format((float)$returncost, 4, '.', '');
    
    }
  

  
  return $returncost;
  
  
//  return $nn;
  
}




function zonearray($key1, $type1) {


$item_array = array();

// loop through $data, exposing $name for later use
foreach ($data as $name => $array) {

    // loop through each named array and set the desired value
    // using the current $key and $name
    foreach ($array as $key => $value) {
        $item_array[$key][$name] = $value;
    }
}

// tada!


echo $item_array[1][$type1];

}


class CheckDevice {
  public function myOS(){
        if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
            return true;
        return false;
  }
  public function ping($ip_addr){
        if ($this->myOS()){
            if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
                return true;
        } else {
            if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
                return true;
        }
        return false;
    }
}

$whitelist = array(
    '127.0.0.1',
    '::1'
);



function is_decimal( $val )
{
    return is_numeric( $val ) && floor( $val ) != $val;
}


function get_days_count_month($month, $code, $doj=null, $dor=null) {
  $timestamp_now = time();
  $date_array = array();
  $days = date('t', strtotime("2022-$month-01"));
  $days = $days + 1;
  $zero = 0;
  for($a = 1; $a < $days; $a++) {
    $day = strlen($a) == 1 ? "0".$a : $a;
    $timestamp = strtotime($month . "-$day");
    $day_code = date("w", $timestamp); 
    // if($timestamp > $timestamp_now)
    //     break;
    if($doj != null){
      if($day_code == $code && strtotime($doj) <= $timestamp && (strtotime($dor) >= $timestamp || $dor == "")){
        @$fridays++;
        $day_date = date("Y-m-d", $timestamp); 
        $date_array[] = $day_date;
        $zero++;
      }
    } else{
      if($day_code == $code){
        @$fridays++;
        $day_date = date("Y-m-d", $timestamp); 
        $date_array[] = $day_date;
      }
    }
  }
  $array[0] = $fridays;
  $array[1] = $date_array;
  $array[2] = $zero;
  return $array;
}


function getDayName($dayOfWeek) {
  switch ($dayOfWeek){
    case 7:
      return 'Sunday';
    case 1:
      return 'Monday';
    case 2:
      return 'Tuesday';
    case 3:
      return 'Wednesday';
    case 4:
      return 'Thrusday';
    case 5:
      return 'Friday';
    case 6:
      return 'Saturday';
    default:
      return '';
  }
}

function hoursandmins($time, $format = '%02d:%02d'){
  if ($time < 1) {
    return 0;
  }
  $hours = floor($time / 60);
  $minutes = ($time % 60);
  return sprintf($format, $hours, $minutes);
}



function get_max_daily_id($table, $date_check, $mode=0, $sales_type=1, $company_id=1, $cost_center=1, $distributor_to_id=0, $transaction_type=0){
  global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;

  $sql = "SELECT MAX(daily_id) AS daily_id FROM $table WHERE 1=1   ";
  if($mode != 0){
    if($table == 'general_receipt' || $table == 'general_payment'){
      $sql .= " AND payment_mode = '$mode' ";
    }
    elseif($table == 'cash_transaction'){
      $sql .= " AND form_type = '$mode' ";
    }
    else{
      $sql .= " AND mode = '$mode' ";
    }
  }
  

  if($table == 'cash_transaction' ){
      $sql .= " AND transaction_type IN (17,69) && `show`=1  ";
    }
  

  if($table == 'warehouse_transaction' ){
      $sql .= " AND atran_type IN ($transaction_type) && `deleted`=0  ";
    }
  
  

  if($distributor_to_id != 0 && $distributor_to_id != ''){
    $distributorColumn = '';
    $datatest = mysqli_query($conn,"SHOW COLUMNS FROM `$table` LIKE 'distributor_id' ") or die(mysqli_error($conn));
    if(mysqli_num_rows($datatest) > 0){
      $distributorColumn = 'distributor_id';
    }else{
      $datatest = mysqli_query($conn,"SHOW COLUMNS FROM `$table` LIKE 'distributor_to_id' ") or die(mysqli_error($conn));
      if(mysqli_num_rows($datatest) > 0){
        $distributorColumn = 'distributor_to_id';
      }
    }
    if($distributorColumn != ''){
      $sql .= " AND $distributorColumn = '$distributor_to_id' ";
    }
  }


  if($company_id != 0 && $company_id != '' && $info2000['serialby_company']==1){
    $sql .= " AND company_id = '$company_id' ";
  }

    if($cost_center != 0 && $cost_center != '' && $info2000['serialby_costcenter']==1){
    $sql .= " AND cost_center = '$cost_center' ";
  }


   if($sales_type != 0 && $sales_type != '' && $info2000['serialby_salestype']==1){


$datatest = mysqli_query($conn,"SHOW COLUMNS FROM `$table` LIKE 'service_invoice' ") or die(mysqli_error($conn));
$numcolumntest = mysqli_num_rows($datatest);
if($numcolumntest==0)  {

    $sql .= " AND sales_type = '$sales_type' ";

  } else {

  $sql .= " AND service_invoice = '$sales_type' ";

  }



  }


if($info2000['serialby_month']==1 && $date_check != 0 && $date_check != ''){
    $sql .= " AND MONTH(`datetime`) = MONTH('$date_check') && AND YEAR(`datetime`) = YEAR('$date_check') ";
  }



 // Fiscal Year Logic
    if($info2000['serialby_year'] == 1 && $date_check != 0 && $date_check != ''){
        // Determine the fiscal year boundaries based on the fiscal_start month-day

        $fiscal_start = $info2000['fiscal_month'];

        $fiscal_start_date = date('Y-m-d', strtotime($fiscal_start));
        $fiscal_start_md = date('m-d', strtotime($fiscal_start_date));
        
        $date_check_md = date('m-d', strtotime($date_check));
        $year_check = date('Y', strtotime($date_check));

        if($date_check_md >= $fiscal_start_md){
            $fiscal_start_year = $year_check;
            $fiscal_end_year = $year_check + 1;
        } else {
            $fiscal_start_year = $year_check - 1;
            $fiscal_end_year = $year_check;
        }

        $fiscal_start_date_bound = "$fiscal_start_year-$fiscal_start_md 00:00:00";
        $fiscal_end_date_bound = "$fiscal_end_year-$fiscal_start_md 00:00:00";

        $sql .= " AND `datetime` >= '$fiscal_start_date_bound' AND `datetime` < '$fiscal_end_date_bound' ";
    }



// echo $sql;

  $result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
  $myrow = mysqli_fetch_array($result);
  return $myrow['daily_id']+1;
}




function get_max_on_record($table, $date_check, $mode=0, $on_record=-1, $distributor_to_id=0){
  global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
  $sql = "SELECT MAX(on_record) AS daily_id FROM $table WHERE 1=1 AND company_id = '$current_company' $date_check ";
  if($mode != 0){
    if($table == 'general_receipt' || $table == 'general_payment'){
      $sql .= " AND payment_mode = '$mode' ";
    }else{
      $sql .= " AND mode = '$mode' ";
    }
  }
  if($info3000['en_litmus'] == 1 && $distributor_to_id != 0){
    $sql .= " AND distributor_to_id = '$distributor_to_id' ";
  }
  if($on_record != -1 ){
    $sql .= " AND on_record = '$on_record'  ";
  }

  $result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
  $myrow = mysqli_fetch_array($result);
  return $myrow['daily_id']+1;
}



















function get_max_daily_id2($table, $date_check, $mode=0, $current_company){
  global $conn;
  $sql = "SELECT MAX(daily_id) AS daily_id FROM $table WHERE 1=1 AND company_id = '$current_company' $date_check ";
  if($mode != 0){
    if($table == 'general_receipt' || $table == 'general_payment'){
      $sql .= " AND payment_mode = '$mode' ";
    }else{
      $sql .= " AND mode = '$mode' ";
    }
  }
  $result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
  $myrow = mysqli_fetch_array($result);
  return $myrow['daily_id']+1;
}





function total_sundays($month)
{
$sundays=0;
$total_days=date('t', strtotime("$month-01"));
for($i=1;$i<=$total_days;$i++)
if(date('N',strtotime($month.'-'.$i))==7)
$sundays++;
return $sundays;
}


function total_saturdays($month)
{
$saturdays=0;
$total_days=date('t', strtotime("$month-01"));
for($i=1;$i<=$total_days;$i++)
if(date('N',strtotime($month.'-'.$i))==6)
$saturdays++;
return $saturdays;
}



function get_month_totaldays($duration){
  global $conn;


$month = date("m", strtotime($duration));

$year = date("Y", strtotime($duration));


// echo get_employee_salary($item, $month, $year)."aaa";
$days_bkp = date('t', strtotime("$year-$month-01"));

return $days = date('t', strtotime("$year-$month-01"));


}




function get_public_holidays($duration, $days){
  global $conn;
  global $payroll_period_start, $payroll_period_end;


if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
  $start = new DateTime($payroll_period_start);
  $end = new DateTime($payroll_period_end);
} else {
  $month = date("m", strtotime($duration));
  $year = date("Y", strtotime($duration));

  $d = $year."-".$month."-"."01";
  $d2 = $year."-".$month."-".$days;
  $ending_date = $d2;

  $start = new DateTime($d);
  $end = new DateTime($d2);
}

// create an iterateable period of date (P1D equates to 1 day)
$period = new DatePeriod($start, new DateInterval('P1D'), $end);

// best stored as array, so you can add more than one
$data15 = mysqli_query($conn,"SELECT * from employee_public_holidays ") or die(mysqli_error($conn));

$holidays = [];
while($info15 = mysqli_fetch_array($data15)) {
    $holiday_raw = trim($info15['holiday']);
    if ($holiday_raw === '') {
        continue;
    }
    $holiday_date = '';
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $holiday_raw)) {
        $holiday_date = $holiday_raw;
    } else if (strpos($holiday_raw, '/') !== false) {
        $date_parts = explode('/', $holiday_raw);
        if (count($date_parts) === 3) {
            $holiday_date = $date_parts[2].'-'.$date_parts[0].'-'.$date_parts[1];
        }
    }
    if ($holiday_date === '') {
        $parsed = strtotime($holiday_raw);
        if ($parsed !== false) {
            $holiday_date = date('Y-m-d', $parsed);
        }
    }
    if ($holiday_date !== '') {
        $holidays[] = $holiday_date;
    }
}

// Fetch employee_working_days data once and store in array
$data14 = mysqli_query($conn, "SELECT * from employee_working_days") or die(mysqli_error($conn));

$working_days = [];
while ($row = mysqli_fetch_array($data14)) {
    $iid = $row['id'];
    $working_days[$iid] = $row;
}

$get_holiday_count = 0;
for($dt = $start; $dt <= $end; $dt->modify('+1 day')) {
    $curr = $dt->format('D');

    foreach ($working_days as $info14) {
        // Check if the day matches and is enabled
        if ($curr == $info14['short_name']) {
            if ($info14['enable'] == 0) {
                // Skip if day is disabled
                break;
            }
            
            // Subtract if holiday and day is enabled
            if (in_array($dt->format('Y-m-d'), $holidays)) {
                $days--;
                $days_bkp--;
                $get_holiday_count++;  // Only increment for working holidays
                break;
            }
        }
    }
}


return $get_holiday_count;

}



function get_loanadjustment($duration, $emp_id){

  global $payroll_period_start, $payroll_period_end;
  if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
    $loan_adj = mysqli_get_var("SELECT SUM(amount) FROM loan_adjustment WHERE emp_id='$emp_id' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' AND loan_type=0 ");
  } else {
    $loan_adj = mysqli_get_var("SELECT SUM(amount) FROM loan_adjustment WHERE emp_id='$emp_id' AND date_format(datetime,'%Y-%m') = '$duration' AND loan_type=0 ");
  }

if($loan_adj=='') $loan_adj=0;

return $loan_adj;

}


function get_advanceadjustment($duration, $emp_id){

global $payroll_period_start, $payroll_period_end;
if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
  $adv_adj = mysqli_get_var("SELECT SUM(amount) FROM loan_adjustment WHERE emp_id='$emp_id' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' AND loan_type=1 ");
} else {
  $adv_adj = mysqli_get_var("SELECT SUM(amount) FROM loan_adjustment WHERE emp_id='$emp_id' AND date_format(datetime,'%Y-%m') = '$duration' AND loan_type=1 ");
}

if($adv_adj=='') $adv_adj=0;
 
return $adv_adj;


}



function get_receipt_incentive_by_date($start_date, $end_date, $employee_id){
  static $has_rice_fields = null;
  static $has_marketing_person = null;
  static $fid_incentive1 = null;
  static $fid_incentive2 = null;

  $employee_id = (int)$employee_id;
  if ($employee_id <= 0) {
    return 0;
  }

  $start_date = trim((string)$start_date);
  $end_date = trim((string)$end_date);
  if ($start_date === '' || $end_date === '') {
    return 0;
  }

  if (strlen($start_date) <= 10) {
    $start_date .= ' 00:00:00';
  }
  if (strlen($end_date) <= 10) {
    $end_date .= ' 23:59:59';
  }

  if ($has_rice_fields === null) {
    $rice_field_table = mysqli_get_var("SHOW TABLES LIKE 'rice_field'");
    $rice_field_details_table = mysqli_get_var("SHOW TABLES LIKE 'rice_field_details'");
    $has_rice_fields = ($rice_field_table !== '' && $rice_field_table !== null && $rice_field_details_table !== '' && $rice_field_details_table !== null);
  }

  if (!$has_rice_fields) {
    return 0;
  }

  if ($fid_incentive1 === null) {
    $fid_incentive1 = mysqli_get_var("SELECT id FROM rice_field WHERE class='recovery_percentageincentive' LIMIT 1");
    if ($fid_incentive1 === '' || $fid_incentive1 === null) {
      $fid_incentive1 = 0;
    }
  }

  if ($fid_incentive2 === null) {
    $fid_incentive2 = mysqli_get_var("SELECT id FROM rice_field WHERE class='recovery_percentageincentive2' LIMIT 1");
    if ($fid_incentive2 === '' || $fid_incentive2 === null) {
      $fid_incentive2 = 0;
    }
  }

  if ($has_marketing_person === null) {
    $has_marketing_person = mysqli_get_var("SHOW COLUMNS FROM `customer` LIKE 'marketing_person'");
  }

  $emp_id_total = 0;
  if ((int)$fid_incentive1 > 0) {
    $emp_id_total = mysqli_get_var("
      SELECT SUM(p.amount * (COALESCE(rfd.value, 0) / 100))
      FROM payment_received p
      INNER JOIN customer c ON c.id = p.cid
      LEFT JOIN rice_field_details rfd
        ON rfd.sid = c.id AND rfd.fid = '$fid_incentive1' AND rfd.stype = 13
      WHERE c.emp_id = '$employee_id'
        AND p.datetime >= '$start_date'
        AND p.datetime <= '$end_date'
    ");
  }

  $marketing_total = 0;
  if ($has_marketing_person && (int)$fid_incentive2 > 0) {
    $marketing_total = mysqli_get_var("
      SELECT SUM(p.amount * (COALESCE(rfd.value, 0) / 100))
      FROM payment_received p
      INNER JOIN customer c ON c.id = p.cid
      LEFT JOIN rice_field_details rfd
        ON rfd.sid = c.id AND rfd.fid = '$fid_incentive2' AND rfd.stype = 13
      WHERE c.marketing_person = '$employee_id'
        AND p.datetime >= '$start_date'
        AND p.datetime <= '$end_date'
    ");
  }

  if ($emp_id_total === '' || $emp_id_total === null) {
    $emp_id_total = 0;
  }
  if ($marketing_total === '' || $marketing_total === null) {
    $marketing_total = 0;
  }

  return (float)$emp_id_total + (float)$marketing_total;
}

function get_salesincentive($duration, $eid){

  global $payroll_period_start, $payroll_period_end;

  if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
    $day_adj = mysqli_get_var("SELECT SUM(total*(salesperson_commission/100)) FROM sales WHERE salesperson_id='$eid' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' ");

    $day_adj2 = mysqli_get_var("SELECT SUM(total*(salesperson_commission2/100)) FROM sales WHERE salesperson_id2='$eid' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' ");

    $day_adj3 = mysqli_get_var("SELECT SUM(total*(salesperson_commission3/100)) FROM sales WHERE salesperson_id3='$eid' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' ");
  } else {
    $day_adj = mysqli_get_var("SELECT SUM(total*(salesperson_commission/100)) FROM sales WHERE salesperson_id='$eid' AND date_format(datetime,'%Y-%m') = '$duration' ");

    $day_adj2 = mysqli_get_var("SELECT SUM(total*(salesperson_commission2/100)) FROM sales WHERE salesperson_id2='$eid' AND date_format(datetime,'%Y-%m') = '$duration' ");

    $day_adj3 = mysqli_get_var("SELECT SUM(total*(salesperson_commission3/100)) FROM sales WHERE salesperson_id3='$eid' AND date_format(datetime,'%Y-%m') = '$duration' ");
  }

  $day_adj = $day_adj + $day_adj2 + $day_adj3;

  if($day_adj=='') $day_adj=0;

  return $day_adj;


}

function get_gratuity($duration, $eid, $gratuity_en, $gratuity_per, $basic_salary, $policy_id)
{
    if($gratuity_en == '1')
    {
        $gr_amount = $basic_salary * ($gratuity_per/100);
        return $gr_amount;
    }
    else
    {
        return 0;    
    }
    
}

function get_leaves_encash($duration, $eid){


return 0;


}


function get_paid_leaves($duration, $eid, $absent_deductleaves, $revised_joining_date, $policy_id, $current_time, $leaves_slab_id, $leaves_leave_id, $leaves_leaves, $leaves_carry, $leaves_encashment, $leaves_encashment_limit ){

// Paid leave count should reflect approved leave days that fall within the selected month.
global $conn;
global $payroll_period_start, $payroll_period_end;

if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
  $periodStart = $payroll_period_start;
  $periodEnd = $payroll_period_end;
} else {
  $periodStart = date('Y-m-01', strtotime($duration.'-01'));
  $periodEnd   = date('Y-m-t', strtotime($duration.'-01'));
}

$leaves = 0;
$sql = "SELECT start_date, end_date 
        FROM employee_leave 
        WHERE eid='$eid' 
          AND approval=1 AND approval2=1
          AND start_date <= '$periodEnd' 
          AND end_date >= '$periodStart'";
$data14 = mysqli_query($conn, $sql) or die(mysqli_error($conn));

while($info14 = mysqli_fetch_array($data14)) { 
  $ftoday2 = date('Y-m-d', strtotime($info14['start_date']));
  $ltoday2 = date('Y-m-d', strtotime($info14['end_date']));

  if (strtotime($ltoday2) > strtotime($periodEnd)) { 
    $ltoday2 = $periodEnd; 
  } 
  if (strtotime($ftoday2) < strtotime($periodStart)) {  
    $ftoday2 = $periodStart; 
  }

  $now = strtotime($ltoday2);  
  $your_date = strtotime($ftoday2); 
  $datediff = $now - $your_date;
  $ll =  ceil($datediff /86400) + 1 ; 
  $leaves += $ll;
}

if($leaves=='' || $leaves<0) { $leaves=0; }

return $leaves;

}


function get_dayadjustment($duration, $eid){

  global $payroll_period_start, $payroll_period_end;
  if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
    $day_adj = mysqli_get_var("SELECT SUM(avalue) FROM attendence_adjustment WHERE emp_id='$eid' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' ");
  } else {
    $day_adj = mysqli_get_var("SELECT SUM(avalue) FROM attendence_adjustment WHERE emp_id='$eid' AND date_format(datetime,'%Y-%m') = '$duration' ");
  }

if($day_adj=='') $day_adj=0;

return $day_adj;


}

function get_employeeattendancedetails($duration, $emp_id, $policy_id, $total_days,$hourly_rate,$employee_shift_day, $employee_shift_id, $employee_shift_time_in, $employee_shift_time_out, $employee_shift_maxentry_time, $employee_shift_maxentry_time2,  
 $employee_shift_maxentry_time3, $employee_shift_enable,  $fullday_hour, $halfday_hour, $lates_allowed, $lates_allowed_type, $entry_aftertime,   $lates_allowed2, $lates_allowed_type2, $entry_aftertime2, $lates_allowed3, $lates_allowed_type3, $entry_aftertime3, $overtime_hourly_rate, $fixed_sunday_hourlyrate, $salary_calculate, $basic_salary, $total_sundays, $total_saturdays , $paid_leaves, $day_adjustment )
 {


global $conn;
global $payroll_period_start, $payroll_period_end;


$present_days = 0;
$total_lates=0; 
$total_halfdays=0; 
$sandwich_deduction = 0;
$absent_daysa = 0;
$available_hours = 0;
$total_hours = 0;
$additional_hours = 0;
$total_hours_amount = 0;
$additional_hours_amount = 0;
$absent_deduction_amount = 0;
$lates_deduction_amount = 0;
$lates_covered = 0;
$gross_salary = 0;

$periodStartDate = '';
$periodEndDate = '';
if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
  $periodStartDate = $payroll_period_start;
  $periodEndDate = $payroll_period_end;
} else {
  $periodStartDate = date('Y-m-01', strtotime($duration.'-01'));
  $periodEndDate = date('Y-m-t', strtotime($duration.'-01'));
}

$periodStartDateTime = $periodStartDate.' 00:00:00';
$periodEndDateTime = $periodEndDate.' 23:59:59';
$total_late_hours = 0;
$total_late_minutes = 0;
$total_fulldays = 0;

$late1 = array();
$late2 = array();
$late3 = array();
$late4 = array();
$late5 = array();


$data14 = mysqli_query($conn,"SELECT max(clock_in) as clock_in, max(clock_out) as clock_out, MIN(add_clock_in) as  add_clock_in ,MAX(add_clock_out) as add_clock_out , max(shift_id) as shift_id from clockin where emp_id='$emp_id' && clock_in >= '$periodStartDateTime' && clock_in <= '$periodEndDateTime' && clock_in!='' && clock_out!='' group by DATE(clock_in) order by clock_in ASC  ") or die(mysqli_error($conn));


    while ($info14 = mysqli_fetch_array($data14)) {
    try {
        $date1 = new DateTime($info14['clock_in']);
        $date2 = new DateTime($info14['clock_out']);
    } catch (Exception $e) {
        continue;
    }
    $shift_id =  $info14['shift_id'];
    $diff2 = $date2->diff($date1);
    $min2 = $diff2->i;
    $hour2 = $diff2->h;
    $work_hours = $hour2 + ($min2 / 60);

    $thours = $thours + $hour2;
    $tmin = $tmin + $min2;



$day_of_week = $date1->format('N');

$count = count($employee_shift_day);


for ($i = 0; $i <= $count; $i++) {

$employee_shift_daya = $employee_shift_day[$i];
$employee_shift_ida = $employee_shift_id[$i];

if($employee_shift_daya==$day_of_week && $employee_shift_ida==$shift_id) {




$employee_shift_time_ina = $employee_shift_time_in[$i];
$employee_shift_time_outa = $employee_shift_time_out[$i];
$employee_shift_maxentry_timea = $employee_shift_maxentry_time[$i];
$employee_shift_maxentry_time2a = $employee_shift_maxentry_time2[$i]; 
$employee_shift_maxentry_time3a = $employee_shift_maxentry_time3[$i];
$employee_shift_enablea = $employee_shift_enable[$i];



 // Convert shift max entry time to DateTime (same day)
            $clock_in_time = DateTime::createFromFormat('H:i:s', $date1->format('H:i:s'));
            if (!$clock_in_time) {
                continue;
            }
            $max_entry_time = DateTime::createFromFormat('H:i:s', $employee_shift_maxentry_timea);
            $max_entry_time2 = DateTime::createFromFormat('H:i:s', $employee_shift_maxentry_time2a);
            $max_entry_time3 = DateTime::createFromFormat('H:i:s', $employee_shift_maxentry_time3a);
            if (!$max_entry_time) {
                $max_entry_time = clone $clock_in_time;
            }
            if (!$max_entry_time2) {
                $max_entry_time2 = clone $clock_in_time;
            }
            if (!$max_entry_time3) {
                $max_entry_time3 = clone $clock_in_time;
            }


 // $sandwich_deduction = $sandwich_deduction.'First Entry: '.$entry_aftertime3.' Second Entry: '.$entry_aftertime2.' 3rd Entry: '.$entry_aftertime.'<br>';

// echo $clock_in_time->format('H:i:s');
// echo "<br>";
// echo $max_entry_time->format('H:i:s');
// echo "-----------------<br>";

// echo "<br>";
// echo "max time 1: ".$max_entry_time;
// echo "<br>";
// echo "max time 2: ".$max_entry_time2;
// echo "<br>";
// echo "max time 3: ".$max_entry_time3;
// echo "<br>";

// Compare clock-in time with max entry time
      if ($clock_in_time > $max_entry_time3) 
       
    //   if ($clock_in_time->format('H:i:s') > $max_entry_time3->format('H:i:s'))
       {
// echo "Yes";
$pp++;
$late1[$pp] = $date1->format('d M Y');
$late2[$pp] = $date1->format('h:i A');
$late3[$pp] = $date2->format('h:i A');
$late4[$pp] = '3rd Late Slab';



$total_lates++;           
  if($lates_allowed3>0)    {  $lates_covered++;  $lates_allowed3--;  $late5[$pp] = 'Exempted';   } else {    


 if($entry_aftertime3==1) { $late5[$pp] = 'Exempted'; } else if($entry_aftertime3==2) { $total_halfdays=$total_halfdays+1; $late5[$pp] = 'Half Day'; } 
 else if($entry_aftertime3==3) { $total_fulldays=$total_fulldays+1; $late5[$pp] = 'Absent'; }  
 else
 {

     // left empty
     $late_diff = $clock_in_time->diff($max_entry_time3);
    $total_late_hours += $late_diff->h;
    $total_late_minutes += $late_diff->i;
    // Convert minutes to hours if they exceed 60
    if($total_late_minutes >= 60) {
        $total_late_hours += floor($total_late_minutes/60);
        $total_late_minutes = $total_late_minutes % 60;
    }
 }
            }
 
}  
else  if ($clock_in_time > $max_entry_time2) 
// else if ($clock_in_time->format('H:i:s') > $max_entry_time2->format('H:i:s'))
{


$pp++;
$late1[$pp] = $date1->format('d M Y');
$late2[$pp] = $date1->format('h:i A');
$late3[$pp] = $date2->format('h:i A');
$late4[$pp] = '2nd Late Slab';

           
$total_lates++;
  if($lates_allowed2>0)    {  $lates_covered++;   $lates_allowed2--;  $late5[$pp] = 'Exempted';    } else {   


 if($entry_aftertime2==1) { $late5[$pp] = 'Exempted'; } else if($entry_aftertime2==2) {$total_halfdays=$total_halfdays+1; $late5[$pp] = 'Exempted'; } 
 else if($entry_aftertime2==3) { $total_fulldays=$total_fulldays+1; $late5[$pp] = 'Exempted'; }
 else { 
    //  left empty
    $late_diff = $clock_in_time->diff($max_entry_time2);
    $total_late_hours += $late_diff->h;
    $total_late_minutes += $late_diff->i;
    // Convert minutes to hours if they exceed 60
    if($total_late_minutes >= 60) {
        $total_late_hours += floor($total_late_minutes/60);
        $total_late_minutes = $total_late_minutes % 60;
    }
     
 }
            }
 
}  
else if ($clock_in_time > $max_entry_time) 
// else if ($clock_in_time->format('H:i:s') > $max_entry_time->format('H:i:s'))
{
// echo "Hi";

$pp++;
$late1[$pp] = $date1->format('d M Y');
$late2[$pp] = $date1->format('h:i A');
$late3[$pp] = $date2->format('h:i A');
$late4[$pp] = '1st Late Slab';


        $total_lates++;   
  if($lates_allowed>0)    { $lates_covered++;   $lates_allowed--;   $late5[$pp] = 'Exempted';  } 
  else 
  {    
     if($entry_aftertime==1) 
     { 
         $late5[$pp] = 'Exempted'; 
     } 
     else if($entry_aftertime==2) 
     {
         $total_halfdays=$total_halfdays+1; $late5[$pp] = 'Half Day'; 
     } 
     else if($entry_aftertime==3) 
     { 
         $total_fulldays=$total_fulldays+1; $late5[$pp] = 'Absent';  
     }
     else 
     { 
         // left empty  
         $late_diff = $clock_in_time->diff($max_entry_time);
    $total_late_hours += $late_diff->h;
    $total_late_minutes += $late_diff->i;
    // Convert minutes to hours if they exceed 60
    if($total_late_minutes >= 60) {
        $total_late_hours += floor($total_late_minutes/60);
        $total_late_minutes = $total_late_minutes % 60;
    }
    
     }
 }
 
} else {


if($work_hours<$halfday_hour) { 

$pp++;
$late1[$pp] = $date1->format('d M Y');
$late2[$pp] = $date1->format('h:i A');
$late3[$pp] = $date2->format('h:i A');
$late4[$pp] = 'Short Hour';
$late5[$pp] = 'Absent';



  $total_fulldays=$total_fulldays+1; 

} else if($work_hours<$fullday_hour) { 


$pp++;
$late1[$pp] = $date1->format('d M Y');
$late2[$pp] = $date1->format('h:i A');
$late3[$pp] = $date2->format('h:i A');
$late4[$pp] = 'Short Hour';
$late5[$pp] = 'Half Day';


  $total_halfdays=$total_halfdays+1; }


} } }



/****
 * extra hours
 */
 
// $add_clock_inext = $info14['add_clock_in'];
// $add_clock_inext = mysqli_get_var("Select MAX(time_out) from employee_shift_details where shift_id = '$shift_id' ");
// $add_clock_outext = $info14['clock_out'];

// if ($add_clock_inext !="" || $add_clock_outext !="") {
    
//     $date3ext = new DateTime($add_clock_inext);
//     $date4ext = new DateTime($add_clock_outext);
//     echo "Start".$add_clock_inext; echo "<br>";
//     echo $add_clock_outext; echo "End<br>";
//     $diff2ext = $date4ext->diff($date3ext);
   
//     $hour2extra = $diff2ext->h;
//      $min2extra = $diff2ext->i;
   
//      $extrahousr += $hour2extra;

//       $extramin += $min2extra;

// }

$add_clock_inext = mysqli_get_var("SELECT MAX(time_out) FROM employee_shift_details WHERE shift_id = '$shift_id'");
$add_clock_outext = $info14['clock_out'];

if ($add_clock_inext != "" && $add_clock_outext != "") {

    // Extract date part from the clock out datetime
    $datePart = date('Y-m-d', strtotime($add_clock_outext));

    // Combine same date with in/out times
    try {
        $datetime_inext  = new DateTime($datePart . ' ' . $add_clock_inext);
        $datetime_outext = new DateTime($add_clock_outext);
    } catch (Exception $e) {
        $datetime_inext = null;
        $datetime_outext = null;
    }

    // Debug prints
    // echo "In Time: " . $datetime_inext->format('Y-m-d H:i:s') . "<br>";
    // echo "Out Time: " . $datetime_outext->format('Y-m-d H:i:s') . "<br>";

    // Calculate difference
    if ($datetime_inext && $datetime_outext) {
        $diff2ext = $datetime_outext->diff($datetime_inext);

        $hour2extra = $diff2ext->h;
        $min2extra  = $diff2ext->i;
        
        // echo "Hours: ".$diff2ext->h; echo "<br>";
        // echo "Mins: ".$diff2ext->i; echo "<br>";
        
        $extrahousr += $hour2extra;
        $extramin   += $min2extra;
        
        if ($extramin >= 60) {
            $extrahousr += floor($extramin / 60);
            $extramin = $extramin % 60;
        }
    }
}



$present_days++;

}

$tmin = floor($tmin%60);

$total_hours = $thours.'hrs : '.$tmin.'min';

$thours = $thours + $tmin;

$extramin = floor($extramin%60);

$additional_hours = $extrahousr.' : '.$extramin;

$total_minutes_ov = ($extrahousr * 60) + $extramin;
$decimal_hours_ov = round($total_minutes_ov / 60, 2);

$extramonthday = $total_sundays + $total_saturdays;


$aaadays = get_month_totaldays($duration);

// If there are clock-ins without clock-out, use them to avoid undercounting present days.
$distinctPresentAll = (int)mysqli_get_var("
    SELECT COUNT(DISTINCT DATE(clock_in))
    FROM clockin
    WHERE emp_id='$emp_id'
      AND clock_in BETWEEN '$periodStartDateTime' AND '$periodEndDateTime'
");
if($distinctPresentAll > $present_days){
  $present_days = $distinctPresentAll;
}

$available_days = $total_days;
$total_period_days = $aaadays;
if (isset($GLOBALS['payroll_period_total_days']) && $GLOBALS['payroll_period_total_days'] !== '') {
  $total_period_days = (int)$GLOBALS['payroll_period_total_days'];
}
if (isset($GLOBALS['payroll_period_available_days']) && $GLOBALS['payroll_period_available_days'] !== '') {
  $available_days = (int)$GLOBALS['payroll_period_available_days'];
}

if($available_days < 0 || $available_days === '') {
  $available_days = 0;
}
if($total_period_days < 0 || $total_period_days === '') {
  $total_period_days = 0;
}

$absent_daysa = $available_days - ($present_days + $paid_leaves + $day_adjustment);
if($absent_daysa < 0) {
  $absent_daysa = 0;
}

if($salary_calculate==1) { 

  if(($available_days)<(($present_days + $day_adjustment - $total_fulldays - ($total_halfdays/2))+$paid_leaves)) { $paid_leaves = ($available_days) - ($present_days + $day_adjustment - $total_fulldays - ($total_halfdays/2)); }

// echo "basic_salary: ".$basic_salary;
// echo "<br>";
// echo "total_days: ".$total_days;
// echo "<br>";
// echo "extramonthday: ".$extramonthday;
// echo "<br>";
// echo "present_days: ".$present_days;
// echo "<br>";
// echo "day_adjustment: ".$day_adjustment;
// echo "<br>";
// echo "total_halfdays: ".$total_halfdays;
// echo "<br>";
// echo "paid_leaves: ".$paid_leaves;
// echo "<br>";
// echo "extramonthday: ".$extramonthday;
// echo "<br>";
// $aaadays = get_month_totaldays($duration);
// echo "total late hrs: ".$total_late_hours;
// echo "<br>";
// echo "total late min: ".$total_late_minutes;
// echo "<br>";

  $salarycal = ($basic_salary/($available_days))*($present_days + $day_adjustment - $total_fulldays - ($total_halfdays/2) +$paid_leaves);
  $gross_salary = $gross_salary + $salarycal;
  $lates_deduction_amount = ($basic_salary/($available_days))*($total_halfdays/2);

//   $absent_deduction_amount = $basic_salary-$gross_salary-$lates_deduction_amount; 

$absent_deduction_amount = ($basic_salary/$available_days)*$absent_daysa;

  if($absent_deduction_amount<0) {  

    if($lates_deduction_amount>0) {

if($lates_deduction_amount<=($absent_deduction_amount*-1)) { $lates_deduction_amount=0; } else { $lates_deduction_amount= $lates_deduction_amount-($absent_deduction_amount*-1);  }

}
    $absent_deduction_amount=0; 

  }

} 
else if($salary_calculate==0) { 

  if(($available_days)<(($present_days + $day_adjustment - $total_fulldays - ($total_halfdays/2))+$paid_leaves)) { $paid_leaves = ($available_days) - ($present_days + $day_adjustment - ($total_halfdays/2)); }

  $paid_non_working_days = $total_period_days - $available_days;
  if($paid_non_working_days < 0) {
    $paid_non_working_days = 0;
  }

  $salarycal = ($basic_salary/$total_period_days)*($present_days + $paid_non_working_days + $day_adjustment - $total_fulldays - ($total_halfdays/2)+$paid_leaves);
  $gross_salary = $gross_salary + $salarycal;
  $lates_deduction_amount = ($basic_salary/$total_period_days)*($total_halfdays/2);
  $absent_deduction_amount = $basic_salary-$gross_salary-$lates_deduction_amount;

  if($absent_deduction_amount<0) {  

    if($lates_deduction_amount>0) {

if($lates_deduction_amount<=($absent_deduction_amount*-1)) { $lates_deduction_amount=0; } else { $lates_deduction_amount= $lates_deduction_amount-($absent_deduction_amount*-1);  }

}
    $absent_deduction_amount=0; 

  }


   }



$total_hours_amount = $thours * $hourly_rate;

// echo "For test: ".$extrahousr; echo "<br>";
// echo "For test: ".$policy_id; echo "<br>";
$policy_overtime = (int)mysqli_get_var("SELECT overtime FROM salary_slab WHERE id = '$policy_id'");
$ovrate = (float)mysqli_get_var("SELECT overtime_rate FROM salary_slab WHERE id = '$policy_id'");
$effective_hourly_rate = 0;

if ($policy_overtime === 1) {
  // Fix rate from employee or hourly rate.
  $effective_hourly_rate = $overtime_hourly_rate > 0 ? $overtime_hourly_rate : $hourly_rate;
} else if ($policy_overtime === 2) {
  // Calculated on salary (per-day salary / full-day hours).
  $salary_days = $available_days + $total_sundays;
  if ((int)$salary_calculate === 1) {
    $salary_days = $available_days;
  } else if ((int)$salary_calculate === 2 && $total_period_days > 0) {
    $salary_days = $total_period_days;
  }

  if ($salary_days > 0) {
    $per_day_salary = $basic_salary / $salary_days;
    if ($fullday_hour > 0) {
      $effective_hourly_rate = $per_day_salary / $fullday_hour;
    }
  }
}

if ($policy_overtime === 0) {
  $effective_hourly_rate = 0;
} else if ($effective_hourly_rate <= 0) {
  $effective_hourly_rate = $overtime_hourly_rate > 0 ? $overtime_hourly_rate : $hourly_rate;
}

if ($policy_overtime === 0) {
  $additional_hours_amount = 0;
} else if ($policy_overtime === 1) {
  // Fix rate uses the overtime_rate multiplier.
  $additional_hours_amount = $effective_hourly_rate * $ovrate * $decimal_hours_ov;
} else {
  // Calculated-on-salary ignores overtime_rate.
  $additional_hours_amount = $effective_hourly_rate * $decimal_hours_ov;
}

// $gross_salary = $gross_salary + $additional_hours_amount;

$formatted_late_time = $total_late_hours . ' hrs ' . $total_late_minutes . ' mins';
// echo $hourly_rate;
return $present_days." | ".$total_lates." | ".$total_halfdays." | ".$sandwich_deduction." | ".$absent_daysa." | ".$available_hours." | ".$total_hours." | ".$additional_hours." | ".$lates_covered." | ".$total_hours_amount." | ".$additional_hours_amount." | ".$absent_deduction_amount." | ".$lates_deduction_amount." | ".$gross_salary." | ".$paid_leaves." | ".json_encode($late1)." | ".json_encode($late2)." | ".json_encode($late3)." | ".json_encode($late4)." | ".json_encode($late5)." | ".$formatted_late_time." | ".$total_late_hours." | ".$total_late_minutes." | ".$total_fulldays;



}


function get_employeeallowance($duration,$aaid, $emp_id, $policy_id, $allowance_type, $is_taxable, $stsalarynet){


global $payroll_period_start, $payroll_period_end;
if (!empty($payroll_period_start) && !empty($payroll_period_end)) {
  $emp_allowance_val = mysqli_get_var("SELECT SUM(avalue) FROM amount_adjustment WHERE emp_id='$emp_id' and allowance='$aaid' AND datetime >= '$payroll_period_start 00:00:00' AND datetime <= '$payroll_period_end 23:59:59' "); 
} else {
  $emp_allowance_val = mysqli_get_var("SELECT SUM(avalue) FROM amount_adjustment WHERE emp_id='$emp_id' and allowance='$aaid' AND MONTH(datetime)=MONTH('$duration') && YEAR(datetime)=YEAR('$duration') "); 
}
$temp_allowance_val =  $temp_allowance_val + $emp_allowance_val;

 if($en_autoallowances==1) {   $autoaval = mysqli_get_var("Select percentage from  salary_slab_autoallowances where slab_id='$policy_id'  && allowances_id='$aaid'  ");  $autoaval = ($autoaval/100) * $stsalarynet;
 }
   else { $autoaval = 0; }


$aval = mysqli_get_var("Select amount from  employee_directallowances where eid='$emp_id'  && aid='$aaid'  ");
  if($aval=='') { $emp_allowance_val=0; } else {

   if($allowance_type==1) { $emp_allowance_val=$aval; } else if($allowance_type==2) { $emp_allowance_val=floor(($aval/($davailable+$sundays))*($dnet+$alates+$sundays2));  } else { $emp_allowance_val=$dpresent*$aval; }  
    }

 $temp_allowance_val =  $temp_allowance_val + $emp_allowance_val;

 if($is_taxable==0) {  $nontax2 = $nontax2 + $temp_allowance_val; }   

 if($temp_allowance_val=='') $temp_allowance_val=0;
if($nontax2=='') $nontax2=0;


return $temp_allowance_val." | ".$nontax2;


}


function get_employee_salesincentive($emp_id){


global $conn;


 if($pfpolicy==0 || $pfpolicy=='') {  $pfpolicy_value=0; } else {  $pfpolicy_value = $gross_salary*($pfpolicy/100);  } 



return $pfpolicy_value;


}



function get_pfdeduction($gross_salary, $pfpolicy){


global $conn;


 if($pfpolicy==0 || $pfpolicy=='') {  $pfpolicy_value=0; } else {  $pfpolicy_value = $gross_salary*($pfpolicy/100);  } 



return $pfpolicy_value;


}

function get_attendance_allowance($duration, $eid, $gross_salary, $policy_id, $allowance_value, $aaid)
{
     global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;
    if($info3000['emp_attendance_allowance'] == '1' && $aaid == '1')
    {
        $att_allowance_amount = $gross_salary * ($allowance_value/100);
        return $att_allowance_amount;
    }
    else
    {
        return 0;    
    }
    
}

function get_taxdeduction($basic_salary, $join=12, $nontax=0, $tax_apply=1){


global $conn;

$taxdeduction = 0;

if($join>12 || $join=='') $join=12;

  $join = (12/$join);


  if($tax_apply==0)  $taxdeduction =0; else {
    $applicableamount = $basic_salary - $nontax;
    $tax12 = $applicableamount*12;



    $data5 = mysqli_query($conn, "SELECT * from  employee_taxslab e where annual_min<='$tax12' && annual_max>='$tax12'  order by annual_min   limit 1 ") or die(mysqli_error());

    while ($info5 = mysqli_fetch_array($data5)) {
        $both=$info5['both_greater'];
        $annual_min=$info5['annual_min'];
        $tax_percent=$info5['tax_percent'];
        $tax_amount=$info5['tax_amount']/(12);
        if ($both==1) {
            $taxdeduction = (($tax12-$annual_min)*($tax_percent/100))/(12);
            $taxdeduction = $taxdeduction + $tax_amount;
        } else {
            $taxdeduction = (($tax12-$annual_min)*($tax_percent/100))/(12);
            if ($taxdeduction<$tax_amount) {
                $taxdeduction=$tax_amount;
            }
        }


       
    }
}
 
if($taxdeduction=='') $taxdeduction=0; 


return $taxdeduction;


}


function get_loanreturn($duration, $emp_id){


global $conn;
global $payroll_period_start, $payroll_period_end;

    $custom1 = $duration."-31";
    if (!empty($payroll_period_end)) {
        $custom1 = $payroll_period_end;
    }


  $data14 = mysqli_query($conn,"SELECT (issued_amount-loan_recovered) AS left_amount, issued_amount as total_mount, return_type, monthly_percent  FROM employee_loan WHERE eid = '$emp_id' AND issued_amount >loan_recovered AND approval = 1 AND approval2 = 1 && execution=1 AND loan_type = 1 AND DATE(datetime) <= DATE('$custom1')  ") or die(mysqli_error($conn));
  $tot_loan_return = 0;
  while($info14 = mysqli_fetch_array( $data14 )){ 
    $left_amount = $info14['left_amount'];
    $total_mount = $info14['total_mount'];
    $return_type = $info14['return_type'];
    $monthly_percent = $info14['monthly_percent']; 
    if($return_type==1){
      $tot_loan_return =  $monthly_percent + $tot_loan_return;
    } else {
      $loanreturn = $total_mount * ($monthly_percent/100);
      $tot_loan_return =  $loanreturn + $tot_loan_return;
    }
  } 

return $tot_loan_return;

}


function get_basicsalary($emp_id, $present_days=0, $max_absent_allow=0){

 global $conn, $current_company, $info1000, $info2000, $info3000, $info4000;


 $data14 = mysqli_query($conn,"SELECT *  FROM employee WHERE id = '$emp_id'   ") or die(mysqli_error($conn));
      
      while($info14 = mysqli_fetch_array( $data14 )){

$basic_salary = $info14['basic_salary'];

if ($info4000['basicsalary_absent']==1) {


$salary_after_absent_deduction = $info14['salary_after_absent_deduction'];

 if ($present_days>$max_absent_allow) {
        $basic_salary= $salary_after_absent_deduction;
    }

}

}

return $basic_salary;

}


function get_advancereturn($duration, $emp_id){

global $conn;
global $payroll_period_start, $payroll_period_end;

$custom1 = $duration."-31";
if (!empty($payroll_period_end)) {
  $custom1 = $payroll_period_end;
}

 $data14 = mysqli_query($conn,"SELECT (issued_amount-loan_recovered) AS left_amount, issued_amount as total_mount, return_type, monthly_percent  FROM employee_loan WHERE eid = '$emp_id' AND issued_amount >loan_recovered AND approval = 1 AND approval2 = 1 && execution=1  AND loan_type = 2 AND DATE(datetime) <= DATE('$custom1')  ") or die(mysqli_error($conn));
      $tot_advance_return = 0;
      while($info14 = mysqli_fetch_array( $data14 )){
        $left_amount = $info14['left_amount'];
          $total_mount = $info14['total_mount'];
          $return_type = $info14['return_type'];
          $monthly_percent = $info14['monthly_percent']; 
          if($return_type==1){
            $tot_advance_return =  $monthly_percent + $tot_advance_return;
          } else {
            $loanreturn = $total_mount * ($monthly_percent/100);
            $tot_advance_return =  $loanreturn + $tot_advance_return;
          }
      } 
 
return $tot_advance_return;


}



function get_policyavailabledays($duration, $days_available, $total_sundays, $count_saturday, $saturday_policy, $public_holidays){


// count_sunday_before_joing + Saturdays before joining

$less_saturday = 0;
if($saturday_policy == 1) {
  $less_saturday = $count_saturday;
} else if($saturday_policy == 4 || $saturday_policy == 5) {
  $less_saturday = floor($count_saturday / 2);
} else if($saturday_policy == 6 || $saturday_policy == 7) {
  $less_saturday = min(1, (int)$count_saturday);
} else if($saturday_policy == 8) {
  $less_saturday = min(2, (int)$count_saturday);
} else if($saturday_policy == 9) {
  $less_saturday = min(3, (int)$count_saturday);
}

$days_available = $days_available-$total_sundays-$less_saturday-$public_holidays;

if($days_available=='') $days_available=0;
if($days_available < 0) $days_available = 0;




return $days_available." | ".$less_saturday;

}


function get_employee_salary($emp_id, $month, $year){
  global $conn;
  if($emp_id == 0 || $month == 0 || $year == 0){
    return 0;
  }else{
    $data559 = mysqli_query($conn,"SELECT * from salary_slab  order by name") or die(mysqli_error($conn));
    $data570 = mysqli_query($conn,"SELECT * from employee_allowances ") or die(mysqli_error($conn));

    $data2 = mysqli_query($conn,"SELECT *, u.id as uid FROM user u,  employee e WHERE u.id=e.id AND e.id = '$emp_id' && u.inactive=0   ") or die(mysqli_error($conn));
    $info2 = mysqli_fetch_array( $data2 );

    $salarynet = $apresent_days = $dlates = $applicableamount = $basic_salary = $basicall = $taxdeduction = $applicableamount = $basic_salary = $basicall =  $tax12  = $taxdeduction = $tax_amount = $totlates = $alates  = $extra_lates  = $dhalf =  $thalfdays = $leaves = $hleaves  = $hleaves2 = $pfpolicy = $totloanreturn  = $nontax = $alates = $aleaves = $sdeduction = $sandwichrule = 0;

    $basic_salary = $info2['basic_salary'];
    $basic_salary_for_show = $info2['basic_salary'];

    $days = date('t', strtotime("$year-$month-01"));
    $duration = $year."-".$month;
    $d = $year."-".$month."-"."01";
    $d2 = $year."-".$month."-".$days;
    $ending_date = $d2;
    
    $start = new DateTime($d);
    $end = new DateTime($d2);

    $period = new DatePeriod($start, new DateInterval('P1D'), $end);

    $get_holiday_count = 0;
    foreach($period as $dt) {
      $curr = $dt->format('D');
      $data14 = mysqli_query($conn,"SELECT * from employee_working_days ") or die(mysqli_error($conn));
      while($info14 = mysqli_fetch_array( $data14 )) { 
      // substract if Saturday or Sunday
        if ($curr == $info14['short_name'] && $info14['enable']==0) {
          $days--;
        }
        else if (in_array($dt->format('Y-m-d'), $holidays)) {
          $days--;
          $get_holiday_count ++;
          break;
        }
      } 
    }
    $days_available=$days;

    mysqli_data_seek( $data559, 0 );
    while($info559 = mysqli_fetch_array( $data559 ))  { 
      if($info2['salary_type']==$info559['id']) {
        $pfpolicy = $info559['provident_amount'];
        $tax_apply = $info559['tax_apply'];
        $lates_allowed = $info559['lates_allowed'];
        $lates_allowed2 = $info559['lates_allowed'];
        $lates_policy =  $lates_allowed_type = $info559['lates_allowed_type'];
        $entry_aftertime = $info559['entry_aftertime'];
        $sandwich_policy = $info559['sandwich_policy'];
        $policy_overtime = $info559['overtime'];
        $policy_minmum_overtime_min = $info559['minimum_overtime'];
        $deduct_sunday = $info559['deduct_sunday']; 
        $salary_calculate = $info559['salary_calculate'];  // Calculate salary on: 1 for working days 0 for all days
        $sunday_calculation = $info559['sunday_calculation']; // Sunday calculation : 1 for standard 0 for hourly 
        $saturday_policy = $info559['saturday_policy'];  //Saturday Policy
        $emp_extra_days = $info559['emp_extra_days']; //Employee Gives Extra Days 1 for yes 0 for No
      } 
    }
    $thovermin = 0;

    $day_adj = mysqli_get_var("SELECT SUM(avalue) FROM attendence_adjustment WHERE emp_id='$emp_id' AND date_format(datetime,'%Y-%m') = '$duration' "); 
    $dtotal = cal_days_in_month(CAL_GREGORIAN,date('m', strtotime($duration)),date('Y', strtotime($duration)));
    $total_month_days = $dtotal;
    $present_days=0;
    $expense_claim = mysqli_get_var("Select SUM(amount) from marketing_expense where  eid='$emp_id' && approval=1 && execution=0   "); 
    $cdate2 = $info2['increment_date'];
    $cdate1 = $d;
    $diff5 = abs(strtotime($cdate2) - strtotime($cdate1));
    $years5 = floor($diff5 / (365*60*60*24));
    $months5 = floor(($diff5 - $years5 * 365*60*60*24) / (30*60*60*24));
    $tmin5 = 0;
    $extra_sunday = 0;
    $sunday_overtime_hours = 0;
    $sunday_overtime = 0;
    $count_friday_plus = 0;
    $count_saturday_plus = 0;
    $count_sunday_plus = 0;
    $count_monday_plus = 0;

    $array = get_days_count_month($duration, 5);
    $count_friday = $array[0];
    $count_friday_date_array = $array[1];

    $array = get_days_count_month($duration, 6);
    $count_saturday = $array[0];
    $count_saturday_date_array = $array[1];

    $array = get_days_count_month($duration, 7);
    $count_sunday = $array[0];
    $count_sunday_date_array = $array[1];

    $array = get_days_count_month($duration, 1);
    $count_monday = $array[0];
    $count_monday_date_array = $array[1];


    $total_working_hours = 0;
    $data14 = mysqli_query($conn,"SELECT max(clock_in) as clock_in, max(clock_out) as clock_out, MIN(add_clock_in) as  add_clock_in ,MAX(add_clock_out) as add_clock_out , max(shift_id) as shift_id from clockin where emp_id='$emp_id' && MONTH(clock_in)=MONTH('$d') &&  YEAR(clock_in)=YEAR('$d') && clock_in!='' && clock_out!='' group by DATE(clock_in) order by clock_in DESC  ") or die(mysqli_error($conn));
    while($info14 = mysqli_fetch_array( $data14 )) { 
      $date1 = new DateTime($info14['clock_in']);
      $date2 = new DateTime($info14['clock_out']);
      $diff2 = $date2->diff($date1);
      $min2 = $diff2->i;
      $hour2 = $diff2->h;
      $thours = $hour1 + $hour2;
      $tmin = $min1 + $min2;
      $total_working_hours += $hour2 + ($min2/60);

      $shift_id = $info14['shift_id'];
      
      $timestamp = strtotime($info14['clock_in']);
      $dd = date('w', $timestamp);
      if($dd==0) 
        $dd=7;
      
      if($day_get == 'Mon')
        $count_monday_plus++;
      if($day_get == 'Fri')
        $count_friday_plus++;
      if($day_get == 'Sat')
        $count_saturday_plus++;
      if($day_get == 'Sun')
        $count_sunday_plus++;
      $day_get = date('D', strtotime($info14['clock_in']));

      if($day_get == 'Sun'){
        $extra_sunday++;
        /*$start_date = new DateTime($info14['clock_in']);
        $since_start = $start_date->diff(new DateTime($info14['clock_out']));
        $sunday_overtime_hours += $since_start->h;*/  
        $date33 = new DateTime($info14['clock_in']);
        $date44 = new DateTime($info14['clock_out']);
        $diff2 = $date44->diff($date33);
        $min2 = $diff2->i;
        $hour2 = $diff2->h;
        $thours = $hour1 + $hour2;
        $tmin = $min1 + $min2;
        $tt = $hour2 + ($min2/60);
        $sunday_overtime_hours = $sunday_overtime_hours + $tt;  
        
        if($sunday_calculation == 1){
          if($info14['add_clock_in']!="" || $info14['add_clock_out']!="") {
            $date3 = new DateTime($info14['add_clock_in']);
            $date4 = new DateTime($info14['add_clock_out']);
            $diff2 = $date4->diff($date3);
            $min2 = $diff2->i;
            $hour2 = $diff2->h;
            $thours = $hour1 + $hour2;
            $tmin = $min1 + $min2;
            $tt = $hour2 + ($min2/60);
            if($policy_overtime != 0){
              $match = $tt*60;
              if($match >= $policy_minmum_overtime_min){
                $thovermin = $thovermin + $tt;  
              }
            }
          }
        }
        
        continue;
      }

      $slabtime_in = mysqli_get_var("Select time_in from employee_shift_details where  shift_id='$shift_id' && day='$dd' "); 
      $slabtime_out = mysqli_get_var("Select time_out from employee_shift_details where  shift_id='$shift_id'  && day='$dd'  "); 
      $max_latetime = mysqli_get_var("Select maxentry_time from employee_shift_details where  shift_id='$shift_id'  && day='$dd'  ");
      $shift_time_in = $slabtime_in;
      $shift_time_out = $slabtime_out;

      $diff = $date2->diff($date1);
      $min1 = $diff->i;
      $hour1 = $diff->h;
      $thours = $hour1;
      $tmin = $min1;
      $max_latetime5 = date('Y-m-d ', strtotime($info14['clock_in'])).' '.$max_latetime;
      $minutes5 =0;

      if ($info14['clock_in']>$max_latetime5) {
        $ci=strtotime($info14['clock_in']);
        $co=strtotime($max_latetime5);
        $minutes5=$ci-$co;
        $minutes5=$minutes5/60;
        if($minutes5>0){
          $tmin5 = $tmin5 + $minutes5; 
        }
      }
      if($overtime==1) {
        $extra_hours = $thours-$min_fullday;
        if($extra_hours>=$minimum_overtime){
          $hovertime = $hovertime + $extra_hours;
          $hovermin = $hovermin + $tmin;    
          $tt = $extra_hours + ($tmin/60);
          $thovermin = $thovermin + $tt;
        }
      }


      if($info14['add_clock_in']!="" || $info14['add_clock_out']!="") {
        $date3 = new DateTime($info14['add_clock_in']);
        $date4 = new DateTime($info14['add_clock_out']);
        $diff2 = $date4->diff($date3);
        $min2 = $diff2->i;
        $hour2 = $diff2->h;
        $thours = $hour1 + $hour2;
        $tmin = $min1 + $min2;
        $tt = $hour2 + ($min2/60);
        if($policy_overtime != 0){
          $match = $tt*60;
          if($match >= $policy_minmum_overtime_min){
            $thovermin = $thovermin + $tt;  
          }
        }
      } 

      $remaining = floor($tmin/60);
      $tmin=$tmin%60;
      $thours+$remaining;   $tmin; 
      $tothours = $tothours + $thours; $totmin = $totmin + $tmin;
      $apresent_days++;  
      $present_days++;    
      $dayname = date('D', strtotime($info14['clock_in']));

      //pk2
      if($thours<=$min_halfday){
        $present_days--;  
        $tnodays++;
      } else if($thours<=$min_fullday ){
          if($dayname!=$halfday_name) {
            $present_days= $present_days-0.5;
            $thalfdays++; 
          }
      }
      else {

        $minlate = date('Y-m-d ', strtotime($info14['clock_in']))."".$max_latetime; 
        $d9 = strtotime($info14['clock_in']);
        $d10 = strtotime($minlate);

        if($d9 >= $d10) {
          $totlates++;
          if($lates_allowed>0){
            $lates_allowed--; 
          }
          else {
            $extra_lates++;
          
            if($lates_policy==1){ }
            else if($lates_policy==2){ $present_days= $present_days-0.5; }
            else if($lates_policy==3) { $present_days--;  }
            else if($lates_policy==4) { //Hourly Rate
              $policy_hourlyrate = 1;
              if($thours>=$min_fullday){
              } else {
                $policy_hour = $policy_hour + $thours;
                $policy_min = $policy_min + $tmin;
              }
            } else {
              $present_days= $present_days;
            }
          }
        }
      }
    } 

    $count_sandwich_days = 0;
    $count_holidays_sunday = mysqli_get_var("Select COUNT(id) from employee_shift_details where  shift_id='$shift_id' && enable = 0 "); 
    $count_friday_date_array;
    $count_saturday_date_array;
    $count_sunday_date_array;
    $count_monday_date_array;
    if($sandwich_policy != 0){
      if($count_holidays_sunday == 1){
        if(COUNT($count_monday_date_array) > COUNT($count_saturday_date_array))
          $plus_one = 1;
        else
          $plus_one = 0;
        for($i=0; $i<COUNT($count_saturday_date_array); $i++){
          $count_record = mysqli_get_var("SELECT COUNT(id) FROM clockin WHERE emp_id = '$emp_id' AND date(clock_in) >= '".$count_saturday_date_array[$i]."' AND date(clock_in) <= '".$count_monday_date_array[$i+$plus_one]."' ");
          if($sandwich_policy == 1){  // half
            if($count_record == 0 || $count_record == 1){
              $count_sandwich_days++;
            }
          }else if($sandwich_policy == 2){  // full
            if($count_record == 0){
              $count_sandwich_days++;
            }
          }
        }
      }else if($count_holidays_sunday == 2){
        if(COUNT($count_monday_date_array) > COUNT($count_friday_date_array))
          $plus_one = 1;
        else
          $plus_one = 0;
        for($i=0; $i<COUNT($count_friday_date_array); $i++){
          $count_record = mysqli_get_var("SELECT COUNT(id) FROM clockin WHERE emp_id = '$emp_id' AND date(clock_in) >= '".$count_friday_date_array[$i]."' AND date(clock_in) <= '".$count_monday_date_array[$i+$plus_one]."' ");
          if($sandwich_policy == 1){  // half
            if($count_record == 0 || $count_record == 1){
              $count_sandwich_days += 2;
            }
          }else if($sandwich_policy == 2){  // full
            if($count_record == 0){
              $count_sandwich_days += 2;
            }
          }
        }
      }
    }

    $newhour = floor($totmin/60); 
    $tothours = $tothours + $newhour;
    $totmin=$totmin%60;
    $newhovertime = floor($hovermin/60);
    $hovertime = $hovertime + $newhovertime;  
    $hovermin=$hovermin%60;
    $tothours= $tothours+$newhour;  
    $leaves=$hleaves=$hleaves2=0;
    $first_day = date('Y-m-1', strtotime($d));
    $last_day = date('Y-m-t', strtotime($d));
    $ftoday = $first_day;
    $ltoday = $last_day;

    $data14 = mysqli_query($conn,"Select start_date, end_date from employee_leave WHERE eid='$emp_id' && ((MONTH(start_date)=MONTH('$d') &&  YEAR(start_date)=YEAR('$d')) || (MONTH(end_date)=MONTH('$d') &&  YEAR(end_date)=YEAR('$d'))   ) && approval=1 && approval2=1 ") or die(mysqli_error($conn));

    while($info14 = mysqli_fetch_array( $data14 )) { 
      $ftoday2 = date('Y-m-d', strtotime($info14['start_date']));
      $ltoday2 = date('Y-m-d', strtotime($info14['end_date']));

      if (strtotime($ltoday2) > strtotime($ltoday)) { 
        $ltoday2 = $ltoday; 
      } 
      if (strtotime($ftoday2) < strtotime($ftoday)) {  
        $ftoday2 = $ftoday; 
      }

      $now = strtotime($ltoday2); // or your date as well 
      $your_date = strtotime($ftoday2); 
      $datediff = $now - $your_date;
      $ll =  ceil($datediff /86400) + 1 ; 
      $leaves = $leaves + $ll;
    }

    $data14 = mysqli_query($conn,"Select start_date, end_date from employee_halfday_req WHERE eid='$emp_id' && ((MONTH(start_date)=MONTH('$d') &&  YEAR(start_date)=YEAR('$d')) || (MONTH(end_date)=MONTH('$d') &&  YEAR(end_date)=YEAR('$d'))   ) && approval=1 && approval2=1 ") or die(mysqli_error($conn));
    while($info14 = mysqli_fetch_array( $data14 )) { 
      $first_day = date('Y-m-1', strtotime($d));
      $last_day = date('Y-m-t', strtotime($d));
      $ftoday = $first_day;
      $ltoday = $last_day;
      $ftoday2 = $info14['start_date'];
      $ltoday2 = $info14['end_date'];
      if ($ftoday2 < $ftoday) { 
        $ftoday2 = $ftoday; 
      }
      if ($ltoday2 > $ltoday) { 
        $ltoday2 = $ltoday; 
      }
      $now = strtotime($ltoday2); // or your date as well
      $your_date = strtotime($ftoday2);
      $datediff = $now - $your_date;
      $hleaves = $hleaves + round($datediff / (60 * 60 * 24))+1;
    }

    $hleaves2=$hleaves; 
    if ($hleaves!=0) 
      $hleaves= $hleaves/2;

      if($saturday_policy == 1){
      $days_available = $days_available-$count_saturday;
      $less_saturday = $count_saturday;
     }else if($saturday_policy == 2 || $saturday_policy == 3){
      $less_saturday = 0;
     }else if($saturday_policy == 4 || $saturday_policy == 5){
      $days_available = $days_available-floor($count_saturday/2);
      $less_saturday = floor($count_saturday/2);
     }else if($saturday_policy == 6 || $saturday_policy == 7){
      $less_saturday = min(1, (int)$count_saturday);
      $days_available = $days_available-$less_saturday;
     }else if($saturday_policy == 8){
      $less_saturday = min(2, (int)$count_saturday);
      $days_available = $days_available-$less_saturday;
     }else if($saturday_policy == 9){
      $less_saturday = min(3, (int)$count_saturday);
      $days_available = $days_available-$less_saturday;
     }
     
     $get_policy_type = mysqli_get_var("SELECT salary_type FROM salary_slab WHERE id = '".$info2['salary_type']."' ");
     if($get_policy_type == 2){      
      $start_date = new DateTime($shift_time_in);
      $since_start = $start_date->diff(new DateTime($shift_time_out));      
      $get_shift_hours = $since_start->h;
      $basic_salary = $info2['hourly_rate']*($get_shift_hours*$days_available);
      $get_total_working_days = $days_available;
     }else if($get_policy_type == 3){
      $basic_salary = $info2['hourly_rate']*($days_available);
      $get_total_working_days = $days_available;
     }  

    $davailable = $days_available; 
    $davailable = $davailable+$get_holiday_count;
    $sundays = $dtotal - $davailable;
    $dpresent = $apresent_days-($hleaves2*0.5);
    $dlates = $totlates; 

    if($lates_allowed_type==0) { 
      $alates = $extra_lates; 
    } else if($lates_allowed_type==5) { 
      $alates=0; 
    } else { 
      $alates = floor(($extra_lates+$lates_allowed2)/($lates_allowed2+1)); 
    } 
    $alates = $alates - $hleaves2;

    if($entry_aftertime==1) { 
      $lates=0; 
    } else if($entry_aftertime==2) {   
      $lates=$alates/2; 
    } else {   
      $lates=$alates; 
    } 

    $dnet = $dpresent-$dhalf-$lates+$leaves+$hleaves; 
    $dnet = $dnet-$count_sandwich_days; 
      
    if($davailable<$dnet && $emp_extra_days == 0) 
      $dnet=$davailable;

    $total_days_employee_present = $total_month_days - $dnet;
    $get_present_days = $dnet;
    $dnet = $dnet + $get_holiday_count;  
    $alates = $dhalf+$lates; $aabsent = $davailable - $dnet - $alates  ; if($aabsent<0) $aabsent=0;

    $sundays2 = ceil($sundays*(($dnet+$alates)/$davailable));
    if($saturday_policy != 2){
      $sundays2 = ceil($sundays*(($dnet+$alates)/($davailable+$less_saturday)));
    }
    $total_days_employee_present = $total_days_employee_present - $sundays2;
    $off = $leaves+$hleaves;
    if($deduct_sunday<=$off) {
      $sdeduction = $sundays;
      $sundays2 = 0;
    }
    $perDaySalary = ($basic_salary/($davailable+$sundays));
    if($salary_calculate == 1){
      $perDaySalary = $basic_salary/$davailable;
    }

    if($dnet!=0) { 
      $salarynet  = ($basic_salary/($davailable+$sundays))*($dnet+$sundays2);
      if($salary_calculate == 1){
        $salarynet  = ($basic_salary/$davailable)*($dnet);
      }
      if($get_policy_type == 2 || $get_policy_type == 3){
        $salarynet  = ($basic_salary/($get_total_working_days))*($get_present_days);
      } 
    } else { 
      $salarynet=0; 
    }

    if($get_policy_type == 2 || $get_policy_type == 3){ 
      $absent_days = ($davailable+$sundays)-($dnet+$sundays2+$get_holiday_count);
      $absent_days = 0;
    }else{
      $absent_days = ($davailable+$sundays)-($dnet+$sundays2);
      if($saturday_policy != 2){
        $absent_days = ($davailable+$sundays)-(($dnet-$less_saturday)+$sundays2);
      }
    }

    mysqli_data_seek( $data570, 0 );
    while($info570 = mysqli_fetch_array( $data570 ))  { 
      $aaid = $info570['id'];
      $allowance_type = $info570['allowance_type']; 
      $is_taxable = $info570['is_taxable'];
      $ajob_status = $info570['job_status'];
      $aval = mysqli_get_var("Select amount from  employee_directallowances where eid='$emp_id'  && aid='$aaid'  ");
      if($aval=='') { 
        $aval=0; 
      } else { 
        if($allowance_type==1) { 
          $aval=$aval; 
        } else if($allowance_type==2) { 
          $aval=floor(($aval/($davailable+$sundays))*($dnet+$alates+$sundays2));  
        } else {
         $aval=$dpresent*$aval; 
       }   
     }
     $salarynet = $salarynet + $aval;
     if($is_taxable==0) { 
      $nontax = $nontax + $aval; 
    }  else { 
      $basicall= $basicall +  $aval;  
    } 
  }

  $aasalary = $basic_salary;  
  $aansalary = mysqli_get_var("SELECT SUM(e.amount) FROM employee_directallowances e, employee_allowances a WHERE a.id=e.aid &&  eid='$emp_id' && allowance_type=2 "); 
  $aasalary1 = $aansalary + $aasalary;    
  $aperday = $aasalary1/30; 
  $aperday2 = $aasalary/($davailable+$sundays);
  if($salary_calculate == 1){
    $aperday2 = $aasalary/($davailable);
  }
  if($get_policy_type == 2 || $get_policy_type == 3){
    $aperday2 = $aasalary/($get_total_working_days);
  }   
  $aasalary1=$aasalary=0; 
  if($get_policy_type == 2 || $get_policy_type == 3){
   
  }else{
    
  }

  $start_date = new DateTime($shift_time_in);
  $since_start = $start_date->diff(new DateTime($shift_time_out));
  if($since_start->h == 0)
    $PerHoursSalary = 0;
  else
      $PerHoursSalary = $perDaySalary/$since_start->h;

  if($info2['overtime_rate_calculation'] == 0 ){
    $hourly_rate2 = 0;
    $thovermin = 0;
  }else if($info2['overtime_rate_calculation'] == 1){ // on fixrate
    $hourly_rate2 = $info2['overtime_hourly_rate'];
  }else{
    $hourly_rate2 = $PerHoursSalary;
  }

  if($salary_policy5!=0) { 
   // echo 0; 
  } else { 
    $deduction_on_lates = $alates*$aperday2; 
  }
  $deduct5=0; 
  if($salary_policy5!=0) { 
    $deduct5 = ($tmin5/60)*$hourly_rate2; 
  }  

  $aa = $thovermin; 
  $extra_hours_for_show = $aa*60;

  $total_hours_rate = $hourly_rate2*$aa;  
  $salarynet = $salarynet+$total_hours_rate-$deduct5;

  if($info2['overtime_calculation'] == 0 ){
    $sunday_overtime_hours = 0;
    $sunday_overtime = 0; 
  }else if($sunday_calculation == 1){
    $sunday_overtime = $extra_sunday*$perDaySalary;
  } else if($info2['overtime_calculation'] == 1){
    $sunday_overtime = $sunday_overtime_hours*$info2['sunday_hourly_rate'];
  }else{
    $sunday_overtime = $sunday_overtime_hours*$PerHoursSalary;

  }
  if($emp_extra_days == 0 && $total_days_employee_present <= 0){
    $sunday_overtime = 0;
  }
  $salarynet += $sunday_overtime;
  if($get_policy_type == 2){ 
    $salarynet = ($info2['hourly_rate']*$total_working_hours)-$deduction_on_lates;
  }

  $amt_adj = mysqli_get_var("SELECT SUM(avalue) FROM amount_adjustment WHERE emp_id='$emp_id' AND date_format(datetime,'%Y-%m') = '$duration' ");
  $salarynet += $amt_adj;
  $salarynet -= $info2['eobi'];
  if($pfpolicy==0 || $pfpolicy=='') { 
  } else {  
    $pfpolicy = $basic_salary*($pfpolicy/100); 
  }
  if($months5==$info2['bonus_duration'] && $info2['bonus_duration']!=0) { 
    $bbonus = $info2['bonus'];  
  } else { 
    $bbonus = 0; 
  } 
  $loan_adj = mysqli_get_var("SELECT SUM(amount) FROM loan_adjustment WHERE emp_id='$emp_id' AND date_format(datetime,'%Y-%m') = '$duration' AND loan_type=0 ");
  $adv_adj  = mysqli_get_var("SELECT SUM(amount) FROM loan_adjustment WHERE emp_id='$emp_id' AND date_format(datetime,'%Y-%m') = '$duration' AND loan_type=1 ");
  
  $custom1 = $duration."-31";
  $data14 = mysqli_query($conn,"SELECT (issued_amount-loan_recovered) AS left_amount, issued_amount as total_mount, return_type, monthly_percent  FROM employee_loan WHERE eid = '$emp_id' AND issued_amount >loan_recovered AND approval = 1 AND approval2 = 1 AND loan_type = 1 AND date(datetime) <= '$custom1'  ") or die(mysqli_error($conn));
  $tot_loan_return = 0;
  while($info14 = mysqli_fetch_array( $data14 )){ 
    $left_amount = $info14['left_amount'];
    $total_mount = $info14['total_mount'];
    $return_type = $info14['return_type'];
    $monthly_percent = $info14['monthly_percent']; 
    if($return_type==1){
      $tot_loan_return =  $monthly_percent + $tot_loan_return;
    } else {
      $loanreturn = $total_mount * ($monthly_percent/100);
      $tot_loan_return =  $loanreturn + $tot_loan_return;
    }
  } 

  if($tot_loan_return > 0){
    $tot_loan_return -= $loan_adj;
  }

  $data14 = mysqli_query($conn,"SELECT (issued_amount-loan_recovered) AS left_amount, issued_amount as total_mount, return_type, monthly_percent  FROM employee_loan WHERE eid = '$emp_id' AND issued_amount >loan_recovered AND approval = 1 AND approval2 = 1 AND loan_type = 2 AND date(datetime) <= '$custom1'  ") or die(mysqli_error($conn));
  $tot_advance_return = 0;
  while($info14 = mysqli_fetch_array( $data14 )){
    $left_amount = $info14['left_amount'];
      $total_mount = $info14['total_mount'];
      $return_type = $info14['return_type'];
      $monthly_percent = $info14['monthly_percent']; 
      if($return_type==1){
        $tot_advance_return =  $monthly_percent + $tot_advance_return;
      } else {
        $loanreturn = $total_mount * ($monthly_percent/100);
        $tot_advance_return =  $loanreturn + $tot_advance_return;
      }
  } 

  if($tot_advance_return > 0){
    $tot_advance_return -= $adv_adj;
  }

  $d11 = new DateTime($current_date);
  $d22 = new DateTime(str_replace(" ", "-", $info2['increment_date']));
  $join = $d11->diff($d22)->m; 
  if($join>12) 
    $join=12;
  $join = (12/$join);
  if($tax_apply==0) 
    $tax =0; 
  else {  
    $applicableamount = $basic_salary+$basicall;   
    $tax12 = $applicableamount*12; 

    $data5 = mysqli_query($conn,"SELECT * from  employee_taxslab e where annual_min<='$tax12' && annual_max>='$tax12'  order by annual_min   limit 1 ") or die (mysqli_error());
    while($info5 = mysqli_fetch_array( $data5 )) {
      $both=$info5['both_greater']; 
      $annual_min=$info5['annual_min'];
      $tax_percent=$info5['tax_percent'];
      $tax_amount=$info5['tax_amount']/(12);
      if($both==1) { 
        $taxdeduction = (($tax12-$annual_min)*($tax_percent/100))/(12);   
        $taxdeduction = $taxdeduction + $tax_amount;   
      } else { 
        $taxdeduction = (($tax12-$annual_min)*($tax_percent/100))/(12); 
        if($taxdeduction<$tax_amount) { 
          $taxdeduction=$tax_amount; 
        } 
      }
    }
  } 

  $netsalary = $salarynet-$pfpolicy-$taxdeduction+$expense_claim+$bbonus-$totloanreturn-$tot_loan_return-$tot_advance_return; 
  // $ntotal = $ntotal + $netsalary;

  return $salarynet;
   
    
  

  }
}

function get_available_quantity($prd_id, $warehouse_id=0, $sub_warehouse_id=0, $type_component=0, $batch=0){
  global $info1000,$info2000; 
  if($prd_id == '' || $prd_id == 0)
    return 0;

  if($warehouse_id != 0)
    $warehouse_sql = "AND warehouse_id = '$warehouse_id' ";
  else
    $warehouse_sql = "AND 1=1 ";

  if($sub_warehouse_id != 0)
    $sub_warehouse_sql = "AND subwarehouse_id = '$sub_warehouse_id' ";
  else
    $sub_warehouse_sql = "AND 1=1 ";

  if($batch != 0){
    $batch_query = " AND batch_no = '$batch'  ";
  }else{
    $batch_query = " AND 1=1  ";
  }

  $a=' SUM(qty) '; 
  $minus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=0 && w.deleted=0 AND type_component = '$type_component' &&  `item_id` = '$prd_id' $warehouse_sql $sub_warehouse_sql $batch_query "); 
    if($info1000['inventory_limit']==1) {
      $minus2 = mysqli_get_var("SELECT $a AS sqty FROM so_details WHERE 1=1 $warehouse_sql && prd_id='$prd_id' && order_id IN (SELECT id FROM so WHERE completed=0 AND type_component = '$type_component')"); 
    }else{
      $minus2 = 0;
    }
    $plus = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && t.type=1 && w.deleted=0 AND type_component = '$type_component' &&  `item_id` = '$prd_id' $warehouse_sql $sub_warehouse_sql $batch_query "); 
    $minus3 = mysqli_get_var("SELECT $a AS sqty FROM warehouse_transaction w, warehouse_transaction_type t WHERE w.tran_type=t.id && w.deleted=0 AND type_component = '$type_component' && (w.tran_type=1 || w.tran_type=21) && verified_by=0 && t.type=1 &&  `item_id` = '$prd_id' $warehouse_sql $sub_warehouse_sql $batch_query ");
    $product_qta=$plus-$minus-$minus2-$minus3;
    if($info2000['qta_inpacking']==0) {
      return $product_qta;
    }else{
      if($type_component == 0)
        $packing5 = mysqli_get_var("SELECT packing FROM inventory WHERE id = '$prd_id' ");
      else if($type_component == 2)
        $packing5 = mysqli_get_var("SELECT packing FROM assets WHERE id = '$prd_id' ");
      else if($type_component == 1)
        $packing5 = mysqli_get_var("SELECT packing FROM component WHERE id = '$prd_id' ");
      
        if($info1000['batch_with_brand']==1){
          $packing5 = mysqli_get_var("SELECT packing FROM inventory_batch WHERE id = '$batch' "); 
          if($packing5=='' || $packing5==0){$packing5 = 1;}
        }

      return ceil($product_qta/$packing5);
    }
}

function get_new_inventory_batch($prd_id, $type_component=0, $batch_code=nulll, $mfg_date=null, $exp_date=null, $extra=null){
  global $conn, $info2000, $current_time;
  if($type_component == 1) 
    $is_batch = mysqli_get_var("SELECT is_batch FROM component WHERE id = '$prd_id' ");
  else if($type_component == 0)
    $is_batch = mysqli_get_var("SELECT is_batch FROM inventory WHERE id = '$prd_id' ");

  if($is_batch == 0){
    return "";
  }else{
    if($info2000['auto_batch_created'] == 1){
      return $current_time;
    }else{
      return "";
    }
  }

  // $batch_id = mysqli_get_var("SELECT COUNT(id) FROM inventory_batch WHERE prd_id = '$prd_id' AND batch_code='$pbatch'  && type_component=0"); 
}


function distributerFrompaymentfifoclear($distributor_id){
  global $conn; 
  $data2 = mysqli_query($conn,"SELECT id AS cid FROM distributor WHERE id = '$distributor_id'   ") or die(mysqli_error($conn));
  $i=1;  $dept_id=0; $company=0; $costcenter=0; 
  while($info2 = mysqli_fetch_array( $data2 )) { 
    $vendor_id=$info2['cid'];
    $tpa = $tpa2 = 0;

    $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM pr_invoice WHERE distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];
    
    
    $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales_debit_note WHERE distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];     
            
    $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM sales_return WHERE distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];     

    $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM sales_credit_note WHERE distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];   

    $query2729=mysqli_query($conn,"SELECT SUM(amount) AS sm FROM payment_received WHERE distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];        
    
    $query2729=mysqli_query($conn,"SELECT SUM(debit) as sm FROM `cash_transaction` WHERE   user_id = '$vendor_id' && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];   
        
    $query2729=mysqli_query($conn,"SELECT SUM(credit) as sm FROM `cash_transaction` WHERE   user_id='$vendor_id' && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];           

    ////////////////////////////////////


    $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM pr_invoice WHERE distributor_to_id =' $vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa2 = $tpa2 + $row['sm'];

    $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM sales_debit_note WHERE distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa2 = $tpa2 + $row['sm'];     
        

    if($tpa==$tpa2 ) { 
    }
    else if($tpa<0) {
      $tpa=$tpa*(-1);

      $sql = "UPDATE pr_invoice SET pending_amount = 0   WHERE distributor_to_id = '$vendor_id'   ";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

      $sql = "UPDATE sales_debit_note SET pending_amount = 0 WHERE distributor_to_id = '$vendor_id'   ";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    } 
    else if($tpa2>$tpa) {
      $customer = $vendor_id;
      $pa=$tpa2-$tpa;
      
      $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, type
        FROM (
          SELECT id, datetime, pending_amount, 1 as type FROM pr_invoice WHERE `distributor_to_id` = '$customer' AND pending_amount!=0
        UNION ALL
          SELECT id, datetime, pending_amount, 2 as type FROM sales_debit_note WHERE `distributor_to_id` = '$customer' AND pending_amount!=0
      ) AS UnionTable
      order BY DATETIME ") or die(mysqli_error($conn));
      while($row = mysqli_fetch_array($result)){
        $pid= $row['id']; 
        $balance= $row['pending_amount'];
        $datetime= $row['datetime'];
        $type= $row['type'];
        $pending=$balance-$pa;
        if ($pending<=0) {
         $pending=0;
        }
        $pa=$pa-$balance;
        if($pa<=0)
          $pa=0;

        if ($type==1){
          $sql = "UPDATE pr_invoice SET pending_amount = '$pending' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
        else if ($type==2) {
          $sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
      }

      if($pa>=0){
        
      }
    } 
    else {
      $cid=$vendor_id;
      $pa=$tpa-$tpa2;
      $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, total, type
        FROM (
          SELECT id, datetime, pending_amount, total, 1 as type FROM pr_invoice WHERE`distributor_to_id` = '$cid' AND pending_amount!=total && id IN (Select invoice_id from payment_record where payment_id='$deptid' && clear_type='1') 
        UNION ALL
          SELECT id, datetime, pending_amount, total, 2 as type FROM sales_debit_note WHERE `distributor_to_id` = '$cid' AND pending_amount!=total
        ) AS UnionTable
        order BY DATETIME Desc ") or die(mysqli_error($conn));
      while($row = mysqli_fetch_array($result)){
        $pid= $row['id']; 
        $balance= $row['pending_amount'];
        $max= $row['total'];
        $datetime= $row['datetime'];
        $type= $row['type'];
        $pending=$balance+$pa;
        if ($pending>=$max) {
          $pending=$max;
        }
        $remainpa=$pending-$balance;
        $pa= $pa-$remainpa;

        if($pa<=0)
          $pa=0;

        if ($type==1){
          $sql = "UPDATE pr_invoice SET pending_amount = pending_amount + '$old_payment' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
        elseif ($type==2) {
          $sql = "UPDATE sales_debit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
      }
      if($pa>=0){
        
      }
    }
  }
}

function distributerTopaymentfifoclear($distributor_id){
  global $conn; 

  $data2 = mysqli_query($conn,"SELECT id as cid FROM distributor WHERE id = '$distributor_id'    ") or die(mysqli_error($conn));
  $i=1;  $dept_id=0; $company=0; $costcenter=0; 
  while($info2 = mysqli_fetch_array( $data2 )) { 
    $vendor_id=$info2['cid'];
    $tpa = $tpa2 = 0;

    $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM purchasing where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];

    $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM purchase_credit_note where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];     

    $query2729=mysqli_query($conn,"SELECT SUM(total_amount) AS sm FROM purchase_returns where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];     

    $query2729=mysqli_query($conn,"SELECT SUM(total) AS sm FROM purchase_debit_note where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];   

    $query2729=mysqli_query($conn,"SELECT SUM(amount) AS sm FROM payment_sent where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];        
        
    $query2729=mysqli_query($conn,"SELECT SUM(credit) as sm FROM `cash_transaction` where   user_id='$vendor_id' && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa + $row['sm'];   
        
    $query2729=mysqli_query($conn,"SELECT SUM(debit) as sm FROM `cash_transaction` where   user_id='$vendor_id' && `show`=1 && transaction_type IN (17, 69) ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa = $tpa - $row['sm'];           

    ////////////////////////////////////

    $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM purchasing where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa2 = $tpa2 + $row['sm'];

    $query2729=mysqli_query($conn,"SELECT SUM(pending_amount) AS sm FROM purchase_credit_note where distributor_to_id = '$vendor_id' ") or die(mysqli_error($conn));
    $row = mysqli_fetch_array($query2729);
    $tpa2 = $tpa2 + $row['sm'];     
        
    if($tpa==$tpa2 ) { 
    }

    else if($tpa<0) {
      $tpa=$tpa*(-1);

      $sql = "UPDATE purchasing SET pending_amount = 0 WHERE distributor_to_id = '$vendor_id'   ";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));

      $sql = "UPDATE purchase_credit_note SET pending_amount = 0 WHERE distributor_to_id = '$vendor_id'   ";
      $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
    } 
    
    else if($tpa2>$tpa) {
      $customer = $vendor_id;
      $pa=$tpa2-$tpa;

      $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, type
        FROM (
        SELECT id, datetime, pending_amount, 1 as type FROM purchasing WHERE `distributor_to_id` = '$customer' AND pending_amount!=0
      UNION ALL
        SELECT id, datetime, pending_amount, 2 as type FROM purchase_credit_note WHERE `distributor_to_id` = '$customer' AND pending_amount!=0
      ) AS UnionTable
      order BY DATETIME ") or die(mysqli_error($conn));
      while($row = mysqli_fetch_array($result)){
        $pid= $row['id']; 
        $balance= $row['pending_amount'];
        $datetime= $row['datetime'];
        $type= $row['type'];
        $pending=$balance-$pa;
        if ($pending<=0) {
          $pending=0;
        }

        $pa=$pa-$balance;
        if($pa<=0)
          $pa=0;

        if ($type==1){
          $sql = "UPDATE purchasing SET pending_amount = '$pending' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
        else if ($type==2) {
          $sql = "UPDATE purchase_credit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
      }

      if($pa>=0){

      }
    } 
    else {
      $cid=$vendor_id;
      $pa=$tpa-$tpa2;

      $result = mysqli_query($conn,"SELECT id, datetime, pending_amount, total, type
        FROM (
          SELECT id, datetime, pending_amount, total_amount as total, 1 as type FROM purchasing WHERE `distributor_to_id` = '$cid' AND pending_amount!=total_amount && id IN (Select invoice_id from ppayment_record where payment_id='$deptid' && clear_type='1') 
        UNION ALL
          SELECT id, datetime, pending_amount, total, 2 as type FROM purchase_credit_note WHERE `distributor_to_id` = '$cid' AND pending_amount!=total
        ) AS UnionTable
        order BY DATETIME Desc ") or die(mysqli_error($conn));
      while($row = mysqli_fetch_array($result)){
        $pid= $row['id']; 
        $balance= $row['pending_amount'];
        $max= $row['total'];
        $datetime= $row['datetime'];
        $type= $row['type'];
        $pending=$balance+$pa;
        
        if ($pending>=$max) {
          $pending=$max;
        }
        $remainpa=$pending-$balance;
        $pa= $pa-$remainpa;

        if($pa<=0)
          $pa=0;

        if ($type==1){
          $sql = "UPDATE purchasing SET pending_amount = pending_amount + '$old_payment' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
        elseif ($type==2) {
          $sql = "UPDATE purchase_credit_note SET pending_amount = '$pending' WHERE id='$pid'" ;
          $retval = mysqli_query($conn, $sql ) or die(mysqli_error($conn));
        }
      }
    }
  }
}


function compress_image($source, $destination, $quality) {
  $info = getimagesize($source);
  if ($info['mime'] == 'image/jpeg')
    $image = imagecreatefromjpeg($source);
  elseif ($info['mime'] == 'image/gif')
    $image = imagecreatefromgif($source);
  elseif ($info['mime'] == 'image/png') 
    $image = imagecreatefrompng($source);

  imagejpeg($image, $destination, $quality);
  return $destination;
}

function get_days_between_dates($date1, $date2){
  $now = strtotime($date2); // or your date as well
  $your_date = strtotime($date1);

  $datediff = $now - $your_date;

  return round($datediff / (60 * 60 * 24));
}

function getOrderTypeName($type_id) {
    switch ($type_id) {
        case 1:
            return "Dine In";
        case 2:
            return "Take Away";
        case 3:
            return "Delivery";
  
    }
}


function getShortMonthNameByNumber($monthNum) {
    switch ($monthNum) {
        case 1:
            return "Jan";
        case 2:
            return "Feb";
        case 3:
            return "Mar";
      case 4:
            return "Apr";
      case 5:
            return "May";
      case 6:
            return "June";
      case 7:
            return "July";
      case 8:
            return "Aug";
      case 9:
            return "Sep";
      case 10:
            return "Oct";
      case 11:
            return "Nov";
      case 12:
            return "Dec";
        // etc
    }
}


function get_batch_out_costing_type_wise($item,$asp_qty){
    global $info2000,$conn;
 
   $batch_array=array();
   $collect_qty=0;
         // echo $aqty." = ".$info2000['costing_type'];
    if($info2000['costing_type']==3)
    {
         // echo "SELECT * from inventory_batch where active=1 AND prd_id='$item' ORDER BY exp_date ASC";
         $data4 = mysqli_query($conn,"SELECT * from inventory_batch where active=1 AND prd_id='$item' ORDER BY exp_date ASC") 
         or die(mysqli_error($conn)); 


        while($info4 = mysqli_fetch_array( $data4 )) {
         $aqty=get_available_quantity($item, 0, 0, 0, $info4['id']);
         if($aqty<=0)
           mysqli_get_var("Update inventory_batch set active='0' where  id='".$info4['id']."'");  
         else
         {  
            
            if($aqty>$asp_qty)
              {
                  $batch_array[$info4['id']] = $asp_qty;
                  break;
              }else{
                    $batch_array[$info4['id']]=$aqty;
                    $asp_qty-=$aqty;
             }

         }


       }
    }

        if($info2000['costing_type']==1)
    {
         // echo "SELECT * from inventory_batch where active=1 AND prd_id='$item' ORDER BY exp_date ASC";
         $data4 = mysqli_query($conn,"SELECT * from inventory_batch where active=1 AND prd_id='$item' ORDER BY id ASC") 
         or die(mysqli_error($conn)); 


        while($info4 = mysqli_fetch_array( $data4 )) {
         $aqty=get_available_quantity($item, 0, 0, 0, $info4['id']);
         if($aqty<=0)
           mysqli_get_var("Update inventory_batch set active='0' where  id='".$info4['id']."'");  
         else
         {  
            
            if($aqty>$asp_qty)
              {
                  $batch_array[$info4['id']] = $asp_qty;
                  break;
              }else{
                    $batch_array[$info4['id']]=$aqty;
                    $asp_qty-=$aqty;
             }

         }


       }
    }

           if($info2000['costing_type']==2)
    {
         // echo "SELECT * from inventory_batch where active=1 AND prd_id='$item' ORDER BY exp_date ASC";
         $data4 = mysqli_query($conn,"SELECT * from inventory_batch where active=1 AND prd_id='$item' ORDER BY id DESC") 
         or die(mysqli_error($conn)); 


        while($info4 = mysqli_fetch_array( $data4 )) {
         $aqty=get_available_quantity($item, 0, 0, 0, $info4['id']);
         if($aqty<=0)
           mysqli_get_var("Update inventory_batch set active='0' where  id='".$info4['id']."'");  
         else
         {  
            
            if($aqty>$asp_qty)
              {
                  $batch_array[$info4['id']] = $asp_qty;
                  break;
              }else{
                    $batch_array[$info4['id']]=$aqty;
                    $asp_qty-=$aqty;
             }

         }


       }
    }



    return $batch_array;

}

 function getaddress($lat,$lng)
  {
     
   ?>
<script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBETJm9ZTOnj1VLg5qHyrqDAMgXwgEKXHc&v=weekly&channel=2"

      async
    ></script>
<script type="text/javascript" >

  const geocoder = new google.maps.Geocoder();

  
const latlng = {
    lat: parseFloat(24.861589416348608),
    lng: parseFloat(67.07082759312756),
  };

  geocoder.geocode({ location: latlng }).then((response) => {
      if (response.results[0]) {
      //  map.setZoom(11);

       

       var aa = response.results[0].formatted_address;
       
      alert(aa); 
      
    
  
</script>
  <?php 
  

     
  }
  
  
  
  function ping($host, $port, $timeout) { 
  $tB = microtime(true); 
  $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
  if (!$fP) { return 0; } 
  $tA = microtime(true); 
  return 1; 
}
  
  
  
 

  function updatestocked($qty,$prodid){
	    
   global $conn; 
  

  $query987 =" update inventory set sync=1   where id='$prodid' ";
    $data987= mysqli_query($conn,$query987) or die(mysqli_error($conn)); 


 
  }

 
 
 function loop($var,$y){
  
  for ($x = 0; $x < $y; $x++) {
	  
  $rec.=0;
}

if($rec=='') { $rec=0; } else { $rec =  substr($rec, 0, -1); $rec='0.'.$rec.'1'; }
  
       return $rec;
}



function syncTableDataInsert($tableName,$days)
{
	
	 global $conn;
	 global $conn2;
	 global $current_company2;
	
  $onlineTableName = $tableName;
	$localTableName = $tableName;


  if($tableName=='so') $onlineTableName='local_so';
	if($tableName=='sales') $onlineTableName='local_sales';
	if($tableName=='sub_customer') $onlineTableName='local_sub_customer';
	if($tableName=='payment_received') $onlineTableName='local_payment_received';

	// Retrieve column information for the online table
    $onlineColumnsQuery = "SHOW COLUMNS FROM `$onlineTableName`";
    $onlineColumnsResult = mysqli_query($conn2, $onlineColumnsQuery);
    $onlineColumns = array();
    if ($onlineColumnsResult) {
        while ($columnRow = mysqli_fetch_assoc($onlineColumnsResult)) {
            $onlineColumns[] = $columnRow['Field'];
        }
    } else {
        die("Failed to retrieve online table columns: " . mysqli_error($conn2));
    }

    // Retrieve column information for the local table
    $localColumnsQuery = "SHOW COLUMNS FROM `$localTableName`";
    $localColumnsResult = mysqli_query($conn, $localColumnsQuery);
    $localColumns = array();
    if ($localColumnsResult) {
        while ($columnRow = mysqli_fetch_assoc($localColumnsResult)) {
            $localColumns[] = $columnRow['Field'];
        }
    } else {
        die("Failed to retrieve local table columns: " . mysqli_error($conn));
    }

    // Compare column structures and identify missing columns
    $missingColumns = array_diff($localColumns, $onlineColumns);

    // Dynamically add missing columns to the online table
    foreach ($missingColumns as $missingColumn) {
        $addColumnQuery = "ALTER TABLE `$onlineTableName` ADD COLUMN `$missingColumn` VARCHAR(255)";
        $addColumnResult = mysqli_query($conn2, $addColumnQuery);
        if ($addColumnResult) {
          //  echo "Added missing column '$missingColumn' to local table!\n";
        } else {
            die("Failed to add missing column '$missingColumn' to local table: " . mysqli_error($conn2));
        }
    }

	
	
	
	if($tableName!='warehouse_transaction' && $tableName!='pos_giftcard') {

	if($tableName=='so') $onlineTableName='local_so';
	if($tableName=='sales') $onlineTableName='local_sales';
	if($tableName=='sub_customer') $onlineTableName='local_sub_customer';
	if($tableName=='payment_received') $onlineTableName='local_payment_received';

    // ACK processed records from online staging back to local system.
    if(in_array($tableName, array('sub_customer','so','sales'), true) && in_array('offline_ref', $onlineColumns, true) && in_array('off_sync_status', $onlineColumns, true)){
      $ackRefs = array();
      $ackQuery = "SELECT offline_ref FROM `$onlineTableName` WHERE off_sync_status = 1 AND offline_ref IS NOT NULL AND offline_ref != '' LIMIT 5000";
      $ackResult = mysqli_query($conn2, $ackQuery);
      if($ackResult){
        while($ackRow = mysqli_fetch_assoc($ackResult)){
          if(!empty($ackRow['offline_ref'])){
            $ackRefs[] = "'" . mysqli_real_escape_string($conn, $ackRow['offline_ref']) . "'";
          }
        }
      }
      if(!empty($ackRefs) && in_array('offline_ref', $localColumns, true)){
        $ackChunks = array_chunk($ackRefs, 400);
        foreach($ackChunks as $chunk){
          $ackUpdate = "UPDATE `$localTableName` SET off_sync_status = 1 WHERE offline_ref IN (" . implode(',', $chunk) . ")";
          mysqli_query($conn, $ackUpdate);
        }
      }
    }
	
	if($tableName=='so') { $localTableName2 = 'so_details';  $onlineTableName2='local_so_details'; } 
	if($tableName=='sales') { $localTableName2 ='sales_details';  $onlineTableName2='local_sales_details'; } 
    // ========================== Matching Details Columns Start ===============================================
      if($tableName=='so' || $tableName=='sales'){
    	    // Retrieve column information for the online table
          $onlineColumnsQuery_detail = "SHOW COLUMNS FROM `$onlineTableName2`";
          $onlineColumnsResult_detail = mysqli_query($conn2, $onlineColumnsQuery_detail);
          $onlineColumns_detail = array();
          if ($onlineColumnsResult_detail) {
              while ($columnRow = mysqli_fetch_assoc($onlineColumnsResult_detail)) {
                  $onlineColumns_detail[] = $columnRow['Field'];
              }
          } else {
              die("Failed to retrieve online table columns: " . mysqli_error($conn2));
          }
      
          // Retrieve column information for the local table
          $localColumnsQuery_detail = "SHOW COLUMNS FROM `$localTableName2`";
          $localColumnsResult_detail = mysqli_query($conn, $localColumnsQuery_detail);
          $localColumns_detail = array();
          if ($localColumnsResult_detail) {
              while ($columnRow = mysqli_fetch_assoc($localColumnsResult_detail)) {
                  $localColumns_detail[] = $columnRow['Field'];
              }
          } else {
              die("Failed to retrieve local table columns: " . mysqli_error($conn));
          }
      
          // Compare column structures and identify missing columns
          $missingColumns = array_diff($localColumns_detail, $onlineColumns_detail);
          // Dynamically add missing columns to the online table
          foreach ($missingColumns as $missingColumn) {
              $addColumnQuery = "ALTER TABLE `$onlineTableName2` ADD COLUMN `$missingColumn` VARCHAR(255)";
              $addColumnResult = mysqli_query($conn2, $addColumnQuery);
              if ($addColumnResult) {
                //  echo "Added missing column '$missingColumn' to local table!\n";
              } else {
                  die("Failed to add missing column '$missingColumn' to local table: " . mysqli_error($conn2));
              }
          }      
      }
    // ========================== Matching Details Columns END =================================================

	  // Storing data To online table
    
    if($tableName=='so' || $tableName=='sales' || $tableName=='sub_customer') {
      $selectQuery = "SELECT * FROM `$localTableName` where 1=1 AND `off_sync_status` != 1 AND offline_ref IS NOT NULL AND offline_ref !='' ORDER BY id ASC limit 150 ";
    }else{
      $selectQuery = "SELECT * FROM `$localTableName` where 1=1 AND `off_sync_status` != 1 ORDER BY id ASC limit 150 ";
    }
    $selectResult = mysqli_query($conn, $selectQuery);
    
    $Table_Ids = array();
    $orderMap = array();

    if ($selectResult) {
        if (mysqli_num_rows($selectResult) > 0) {
          // ====================================== Main Insert Start
          while ($row = mysqli_fetch_assoc($selectResult)) {
            $localRowId = isset($row['id']) ? (int)$row['id'] : 0;
            $offlineRef = isset($row['offline_ref']) ? trim($row['offline_ref']) : '';
            if($localRowId > 0){
              $Table_Ids[] = $localRowId;
            }

            $remoteRowId = 0;

            if($offlineRef != ''){
              $offlineRefEsc2 = mysqli_real_escape_string($conn2, $offlineRef);
              $existingRowResult = mysqli_query($conn2, "SELECT id FROM `$onlineTableName` WHERE offline_ref = '$offlineRefEsc2' LIMIT 1");
              if($existingRowResult && mysqli_num_rows($existingRowResult) > 0){
                $existingRow = mysqli_fetch_assoc($existingRowResult);
                $remoteRowId = (int)$existingRow['id'];
              }
            }

            if($remoteRowId > 0){
              $updateParts = array();
              foreach ($row as $columnName => $columnValue) {
                if($columnName === 'id'){ continue; }
                if($columnName === 'sync'){
                  $updateParts[] = "`$columnName` = 0";
                  continue;
                }
                if($columnName === 'off_sync_status'){
                  $updateParts[] = "`$columnName` = 0";
                  continue;
                }
                if($columnValue === null){
                  $updateParts[] = "`$columnName` = NULL";
                }else{
                  $updateParts[] = "`$columnName` = '" . mysqli_real_escape_string($conn2, $columnValue) . "'";
                }
              }
              if(!empty($updateParts)){
                $updateQuery = "UPDATE `$onlineTableName` SET " . implode(', ', $updateParts) . " WHERE id = '$remoteRowId'";
                mysqli_query($conn2, $updateQuery);
              }
            } else {
              // Prepare column names and values for the online table insert
              $columnNames = array();
              $columnValues = array();
              foreach ($row as $columnName => $columnValue) {
                $columnNames[] = $columnName;
                if ($columnName === 'id') {
                  $columnValues[] = 'NULL';
                } else if ($columnName === 'sync') {
                  $columnValues[] = '0';
                } else if ($columnName === 'off_sync_status') {
                  $columnValues[] = '0';
                } else if ($columnValue === null) {
                  $columnValues[] = 'NULL';
                } else {
                  $columnValues[] = "'" . mysqli_real_escape_string($conn2, $columnValue) . "'";
                }
              }
              $insertQuery = "INSERT INTO `$onlineTableName` (`" . implode("`, `", $columnNames) . "`) VALUES (" . implode(", ", $columnValues) . ")";
              $insertResult = mysqli_query($conn2, $insertQuery);
              if($insertResult){
                $remoteRowId = mysqli_insert_id($conn2);
              }
            }

            if(($tableName=='so' || $tableName=='sales') && $localRowId > 0 && $remoteRowId > 0){
              $orderMap[] = array(
                'local_id' => $localRowId,
                'remote_id' => $remoteRowId,
                'offline_ref' => $offlineRef
              );
            }
          }
          // ====================================== Main Insert END

          // ====================================== Detail Insert Start
          if(($tableName=='so' || $tableName=='sales') && !empty($orderMap) ) {
            foreach($orderMap as $orderRow){
              $localRowId = (int)$orderRow['local_id'];
              $remoteRowId = (int)$orderRow['remote_id'];
              $offlineRef = $orderRow['offline_ref'];

              if($remoteRowId <= 0){
                continue;
              }

              if($offlineRef != ''){
                $offlineRefEsc2 = mysqli_real_escape_string($conn2, $offlineRef);
                $deleteQuery2 = "DELETE FROM `$onlineTableName2` WHERE offline_ref = '$offlineRefEsc2'";
                mysqli_query($conn2, $deleteQuery2);
                $selectQuery2 = "SELECT * FROM `$localTableName2` WHERE offline_ref = '" . mysqli_real_escape_string($conn, $offlineRef) . "'";
              } else {
                $deleteQuery2 = "DELETE FROM `$onlineTableName2` WHERE order_id = '$remoteRowId'";
                mysqli_query($conn2, $deleteQuery2);
                $selectQuery2 = "SELECT * FROM `$localTableName2` WHERE order_id = '$localRowId'";
              }

              $selectResult2 = mysqli_query($conn, $selectQuery2);
              if ($selectResult2) {
                while ($row2 = mysqli_fetch_assoc($selectResult2)) {
                  // Prepare column names and values for the online table insert
                  $columnNames2 = array();
                  $columnValues2 = array();
                  foreach ($row2 as $columnName2 => $columnValue2) {
                    $columnNames2[] = $columnName2;
                    if ($columnName2 == 'id') {
                      $columnValues2[] = "NULL";
                    } else if ($columnName2 == 'order_id') {
                      $columnValues2[] = "'" . $remoteRowId . "'";
                    } else if ($columnName2 == 'sync') {
                      $columnValues2[] = "0";
                    } else if ($columnName2 == 'off_sync_status') {
                      $columnValues2[] = "0";
                    } else if ($columnValue2 === null) {
                      $columnValues2[] = "NULL";
                    } else {
                      $columnValues2[] = "'" . mysqli_real_escape_string($conn2, $columnValue2) . "'";
                    }
                  }

                  $insertQuery2 = "INSERT INTO `$onlineTableName2` (`" . implode("`, `", $columnNames2) . "`) VALUES (" . implode(", ", $columnValues2) . ")";
                  mysqli_query($conn2, $insertQuery2);
                }
              }
            }
          } 
          // ====================================== Detail Insert END

          if(!empty($Table_Ids)){
            $Table_Ids_int = array_map('intval', $Table_Ids);
            $Table_Ids_combine = implode(',',$Table_Ids_int);
            if($tableName=='sub_customer') {		
              $truncateQuery3 = "Update sub_customer set off_sync_status = CASE WHEN off_sync_status = 1 THEN 1 ELSE 2 END where id IN ($Table_Ids_combine) ";
              mysqli_query($conn, $truncateQuery3);
            }	
            
            if($tableName=='so') {
              $truncateQuery3 = "Update so set off_sync_status = CASE WHEN off_sync_status = 1 THEN 1 ELSE 2 END where id IN ($Table_Ids_combine) ";
              mysqli_query($conn, $truncateQuery3);
            }
            
            if($tableName=='sales') {
              $truncateQuery3 = "Update sales set off_sync_status = CASE WHEN off_sync_status = 1 THEN 1 ELSE 2 END where id IN ($Table_Ids_combine) ";
              mysqli_query($conn, $truncateQuery3);
            }  
          }
           	
        } 
    }  
  }			
}

function syncTableDataSync($tableName,$days)
{
	
	 global $conn;
	 global $conn2;
	 global $current_company2;
	
    $localTableName = $tableName;
    $onlineTableName = $tableName;
	
	

	
	
	 if($tableName!='warehouse_transaction'  && $tableName!='pos_giftcard' && $tableName!='sub_customer' && $tableName!='inventory' ) {
    // Truncate local table
    $truncateQuery = "TRUNCATE TABLE $localTableName";
    $truncateResult = mysqli_query($conn, $truncateQuery);
    if ($truncateResult) {
       // echo "Local table $localTableName truncated!\n";
    } else {
        die("Failed to truncate local table: " . mysqli_error($conn));
    }
	
  }
	
	
	
	

	
	if($tableName=='warehouse_transaction' || $tableName=='pos_giftcard' || $tableName=='sub_customer'  || $tableName=='so' || $tableName=='sales' || $tableName=='payment_received') {
		
		//  $cc =  " && id>'$days'  "; 
    $cc =  " AND DATE(`datetime`)>=DATE('$days')  "; 

    }
	
	
	if($tableName=='inventory' ) { 
	
	 $data20 = mysqli_query($conn2,"SELECT pos_updated as max from main2 ") or die(mysqli_error($conn2));
  		$info20 = mysqli_fetch_array( $data20 );
		 $last_date=$info20['max']; 
	
		$cc =  " && ( id>'$days' || last_date>'$last_date' )  "; }
	
	// Retrieve data from online table
 $selectQuery = "SELECT * FROM $onlineTableName WHERE 1=1 $cc";
//  echo $selectQuery;
//  die('');
$selectResult = mysqli_query($conn2, $selectQuery);

    if (mysqli_num_rows($selectResult) > 0) {
        $batchSize = 1000; // Number of records to insert in each batch
        $rowCount = 0;
        $insertColumns = array();
        $insertValues = array();
        
        while ($row = mysqli_fetch_assoc($selectResult)) {
            // Prepare column names and values for the local table insert
            $columnNames = array();
            $columnValues = array();
            foreach ($row as $columnName => $columnValue) {
                $columnNames[] = $columnName;
                $columnValues[] = "'" . mysqli_real_escape_string($conn, $columnValue) . "'";
            }
            
            // Build and execute the insert query to insert data into the local table
            $insertQuery = "INSERT INTO $localTableName (`" . implode("`, `", $columnNames) . "`) VALUES (" . implode(", ", $columnValues) . ")";
            $insertResult = mysqli_query($conn, $insertQuery);
            
            if (!$insertResult) {
                die("Failed to insert data into local table: ". $localTableName . mysqli_error($conn));
            }
            
            $rowCount++;
            
            
            
            // Insert the batch when the batch size is reached
            if ($rowCount % $batchSize === 0) {
                // Reset the insert values array for the next batch
                $insertValues = array();
            }
        }
        
      //  echo "Sync completed: Online data inserted into the local table.";
    } 
	


	if ($tableName == 'so' || $tableName == 'sales') {
                $onlineTableName2 = ($tableName == 'so') ? 'so_details' : 'sales_details';
				
				
	 $truncateQuery = "TRUNCATE TABLE $onlineTableName2";
   $truncateResult = mysqli_query($conn, $truncateQuery);
                
                // Retrieve data from online table
                $selectQuery2 = "SELECT * FROM $onlineTableName2 WHERE order_id IN (SELECT id FROM $onlineTableName WHERE 1=1 $cc ) ";
                $selectResult2 = mysqli_query($conn2, $selectQuery2);
                
                if ($selectResult2) {
                    if (mysqli_num_rows($selectResult2) > 0) {
                        $insertColumns2 = array();
                        $insertValues2 = array();
                        
                        while ($row2 = mysqli_fetch_assoc($selectResult2)) {
                            // Prepare column names and values for the local table insert
                            $columnNames2 = array();
                            $columnValues2 = array();
                            foreach ($row2 as $columnName2 => $columnValue2) {
                                $columnNames2[] = $columnName2;
                                $columnValues2[] = "'" . mysqli_real_escape_string($conn, $columnValue2) . "'";
                            }
                            
                            // Build and execute the insert query to insert data into the local table
                            $insertQuery2 = "INSERT INTO $onlineTableName2 (`" . implode("`, `", $columnNames2) . "`) VALUES (" . implode(", ", $columnValues2) . ")";
                            // echo $insertQuery2."<br>";
                            $insertResult2 = mysqli_query($conn, $insertQuery2);
                            
                            if (!$insertResult2) {
                                die("Failed to insert data into local table: ". $localTableName2 . mysqli_error($conn));
                            }
                        }
                    }
                }
            }
   
		
	
}

  
  function syncTableDataOnline_old($tableName,$days)
{
	
	 global $conn;
	 global $conn2;
	
    $localTableName = $tableName;
    $onlineTableName = $tableName;
	
	
	
	    // Retrieve column information for the online table
    $onlineColumnsQuery = "SHOW COLUMNS FROM $onlineTableName";
    $onlineColumnsResult = mysqli_query($conn2, $onlineColumnsQuery);
    $onlineColumns = array();
    if ($onlineColumnsResult) {
        while ($columnRow = mysqli_fetch_assoc($onlineColumnsResult)) {
            $onlineColumns[] = $columnRow['Field'];
        }
    } else {
        die("Failed to retrieve online table columns: " . mysqli_error($conn2));
    }

    // Retrieve column information for the local table
    $localColumnsQuery = "SHOW COLUMNS FROM $localTableName";
    $localColumnsResult = mysqli_query($conn, $localColumnsQuery);
    $localColumns = array();
    if ($localColumnsResult) {
        while ($columnRow = mysqli_fetch_assoc($localColumnsResult)) {
            $localColumns[] = $columnRow['Field'];
        }
    } else {
        die("Failed to retrieve local table columns: " . mysqli_error($conn));
    }

    // Compare column structures and identify missing columns
    $missingColumns = array_diff($onlineColumns, $localColumns);

    // Dynamically add missing columns to the local table
    foreach ($missingColumns as $missingColumn) {
        $addColumnQuery = "ALTER TABLE $localTableName ADD COLUMN $missingColumn VARCHAR(255)";
        $addColumnResult = mysqli_query($conn, $addColumnQuery);
        if ($addColumnResult) {
            echo "Added missing column '$missingColumn' to local table!\n";
        } else {
            die("Failed to add missing column '$missingColumn' to local table: " . mysqli_error($conn));
        }
    }

	
	
	
	if($tableName!='warehouse_transaction') {
	
	
	 // Insert data from local to online where branchcode does not exist in online table
    $insertQuery = "INSERT INTO $onlineTableName SELECT * FROM $localTableName WHERE branchcode NOT IN (SELECT branchcode FROM $onlineTableName)";
    mysqli_query($conn2, $insertQuery);
    
    
	
	// Truncate local table
    $truncateQuery = "TRUNCATE TABLE $localTableName";
    mysqli_query($conn, $truncateQuery);
   
	}
	
	
	
	if($tableName=='warehouse_transaction') { $cc =  " && id>'$days'  "; }
	
	
	if($tableName=='so' || $tableName=='sales' || $tableName=='payment_received') { 
	
	$dd = date('Y-m-d', strtotime('-'.$days.'days'));


	
	$cc =  " &&  DATE(`datetime`)>=DATE('$dd')   "; }
	
	  // Retrieve data from online table
     $selectQuery = "SELECT * FROM $onlineTableName where 1=1 $cc  ";
    $selectResult = mysqli_query($conn2, $selectQuery);
    if ($selectResult) {
        if (mysqli_num_rows($selectResult) > 0) {
            while ($row = mysqli_fetch_assoc($selectResult)) {
                // Prepare column names and values for the local table insert
                $columnNames = array();
                $columnValues = array();
                foreach ($row as $columnName => $columnValue) {
                    $columnNames[] = $columnName;
                    $columnValues[] = "'" . mysqli_real_escape_string($conn, $columnValue) . "'";
                }

                // Build and execute the insert query to insert data into the local table
               $insertQuery = "INSERT INTO $localTableName (`" . implode("`, `", $columnNames) . "`) VALUES (" . implode(", ", $columnValues) . ")";
$insertResult = mysqli_query($conn, $insertQuery);

		
		if($tableName=='so') { $onlineTableName2=' so_details'; } 
		if($tableName=='sales') { $onlineTableName2=' sales_details'; } 
		
		$insvalue = $columnValues[0];

if($tableName=='so' || $tableName=='sales' ) { 

				 // Retrieve data from online table
      $selectQuery2 = "SELECT * FROM $onlineTableName2 where order_id=$insvalue  ";
    $selectResult2 = mysqli_query($conn2, $selectQuery2);
    if ($selectResult2) {
        if (mysqli_num_rows($selectResult2) > 0) {
            while ($row2 = mysqli_fetch_assoc($selectResult2)) {
                // Prepare column names and values for the local table insert
                $columnNames2 = array();
                $columnValues2 = array();
                foreach ($row2 as $columnName2 => $columnValue2) {
                    $columnNames2[] = $columnName2;
                    $columnValues2[] = "'" . mysqli_real_escape_string($conn, $columnValue2) . "'";
                }

                // Build and execute the insert query to insert data into the local table
               $insertQuery2 = "INSERT INTO $onlineTableName2 (`" . implode("`, `", $columnNames2) . "`) VALUES (" . implode(", ", $columnValues2) . ")";
               $insertResult2 = mysqli_query($conn, $insertQuery2);                
          }
        } 
	    }
    } 
				
				
               
            }
        } 
    } 
    
   
		
	
}
  
  
function syncTableData($tableName,$days)
{
	
	 global $conn;
	 global $conn2;
	
    $localTableName = $tableName;
   $onlineTableName = $tableName;

    // Retrieve column information for the online table
    $onlineColumnsQuery = "SHOW COLUMNS FROM $onlineTableName";
    $onlineColumnsResult = mysqli_query($conn2, $onlineColumnsQuery);
    $onlineColumns = array();
    if ($onlineColumnsResult) {
        while ($columnRow = mysqli_fetch_assoc($onlineColumnsResult)) {
            $onlineColumns[] = $columnRow['Field'];
        }
    } else {
        die("Failed to retrieve online table columns: " . mysqli_error($conn2));
    }

    // Retrieve column information for the local table
    $localColumnsQuery = "SHOW COLUMNS FROM $localTableName";
    $localColumnsResult = mysqli_query($conn, $localColumnsQuery);
    $localColumns = array();
    if ($localColumnsResult) {
        while ($columnRow = mysqli_fetch_assoc($localColumnsResult)) {
            $localColumns[] = $columnRow['Field'];
        }
    } else {
        die("Failed to retrieve local table columns: " . mysqli_error($conn));
    }

    // Compare column structures and identify missing columns
    $missingColumns = array_diff($onlineColumns, $localColumns);

    // Dynamically add missing columns to the local table
    foreach ($missingColumns as $missingColumn) {
        $addColumnQuery = "ALTER TABLE $localTableName ADD COLUMN $missingColumn VARCHAR(255)";
        $addColumnResult = mysqli_query($conn, $addColumnQuery);
        if ($addColumnResult) {
        //    echo "Added missing column '$missingColumn' to local table!\n";
        } else {
            die("Failed to add missing column '$missingColumn' to local table: " . mysqli_error($conn));
        }
    }


  if($tableName!='warehouse_transaction' && $tableName!='pos_giftcard' && $tableName!='sub_customer' && $tableName!='inventory' ) {
    // Truncate local table
    $truncateQuery = "TRUNCATE TABLE $localTableName";
    $truncateResult = mysqli_query($conn, $truncateQuery);
    if ($truncateResult) {
       // echo "Local table $localTableName truncated!\n";
    } else {
        die("Failed to truncate local table: " . mysqli_error($conn));
    }
	
  }

if($tableName=='warehouse_transaction'  || $tableName=='pos_giftcard' || $tableName=='sub_customer' || $tableName=='inventory' ) { $cc =  " && id>'$days'  "; }

$selectQuery = "SELECT * FROM $onlineTableName where 1=1 $cc   ";
$selectResult = mysqli_query($conn2, $selectQuery);

mysqli_begin_transaction($conn);

if ($selectResult) {
    if (mysqli_num_rows($selectResult) > 0) {
        $batchSize = 1000; // Number of records to insert in each batch
        $rowCount = 0;
        $insertColumns = array();
        $insertValues = array();
        
        while ($row = mysqli_fetch_assoc($selectResult)) {
          		  
		    // Get the primary ID from the row
        // if($tableName=='inventory' ) {    $primary_id = $row['id'];
        //     $insertQuery = "Delete from $localTableName where id='$primary_id' ";
        //     $insertResult = mysqli_query($conn, $insertQuery);		  
        // }		
		  
    		    if (empty($insertColumns)) {
                // Get the column names from the first row
                $insertColumns = array_keys($row);
            }
            
            $columnValues = array();
            
            foreach ($row as $columnValue) {
                $columnValues[] = "'" . mysqli_real_escape_string($conn, $columnValue) . "'";
            }
            
            $insertValues[] = "(" . implode(", ", $columnValues) . ")";
            
            $rowCount++;
            
            // Insert the batch when the batch size is reached
            if ($rowCount % $batchSize === 0) {
                $insertQuery = "INSERT INTO $localTableName (`" . implode("`, `", $insertColumns) . "`) VALUES " . implode(", ", $insertValues);
                $insertResult = mysqli_query($conn, $insertQuery);
                
				
                if (!$insertResult) {
                  mysqli_rollback($conn);
                  die("Failed to insert data into local table: ". $localTableName . mysqli_error($conn));
                }
                
                // Reset the insert values array for the next batch
                $insertValues = array();
            }
        }
        
        // Insert any remaining records in the last batch
        if (!empty($insertValues)) {
            $insertQuery = "INSERT INTO $localTableName (`" . implode("`, `", $insertColumns) . "`) VALUES " . implode(", ", $insertValues);
            $insertResult = mysqli_query($conn, $insertQuery);
            
            if (!$insertResult) {
              mysqli_rollback($conn);
              die("Failed to insert data into local table: " . $localTableName . mysqli_error($conn));
            }
        }
        mysqli_commit($conn);
 //       echo "Sync completed: Online data inserted into the local table.";
    } else {
   //     echo "No data found in the online table.\n";
    }
} else {
  mysqli_rollback($conn);
      die("Failed to retrieve data from online table: " . mysqli_error($conn2));
}

}


function get_names_of_columns($table, $feild_name, $column_id, $id){
    global $conn;
    $sql = " SELECT $feild_name AS name FROM $table WHERE $column_id = '$id' ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $row = mysqli_fetch_array($res);
    return $row['name'];
  }

  function get_demoplot_pogress_by_date($item_id, $date, $user_id, $team){
    global $conn, $current_company2;
    $sql = " SELECT Count(id) AS count FROM demo_plot WHERE date(submit_date) = '$date' AND item_id = '$item_id' ";
    if($user_id != 'a')
        $sql .= " AND eid IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1  ) ";
    elseif($team != "a")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."') ) ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return $rows['count'];
  }


  function get_sample_by_date($item_id, $date, $user_id, $team, $hospital){
    global $conn, $current_company2, $loginuser;
    $sql = " SELECT SUM(d.qty) AS qty from demo_plot d, inventory i where d.item_id=i.id AND date(d.datetime) = '$date' ";
    if($item_id != 0)
        $sql .= " AND d.item_id = '$item_id' ";
    if($user_id != 'a')
      $sql .= " AND d.eid IN ('".str_replace("a, "," ",$user_id)."') ";
    if($en_user == 1){
          $sql .= "";
        }else{
          $sql .= $limituser78;
        }
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND d.eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "a")
      $sql .= " AND d.eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."') ) ";
    if($hospital != "a")  
      $sql .= " AND d.uid IN (SELECT id FROM user WHERE company_name IN('".str_replace(", ", "','",str_replace("a, ","",$hospital))."'))";

    //echo $sql;
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));

    $rows = mysqli_fetch_array($res);
    return ($rows['qty'])? $rows['qty'] : 0;
  }


function get_visits_by_date($did, $date, $user_id="a", $team="a"){
    global $conn, $current_company2;
    $sql = " SELECT COUNT(id) AS COUNT FROM `call_report` WHERE date(datetime) = '$date' ";
    if($did != 0)
        $sql.= " AND eid = '$did' ";
    if($user_id != 'a')
        $sql.= " AND eid IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "a")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."')) ";    
    
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['COUNT'])? $rows['COUNT'] : 0;
  }



function get_visits_by_doctor($uid, $did, $date1, $date2, $types, $usr=0, $team=""){
    global $conn,$current_company2;
    $sql = " SELECT COUNT(id) AS COUNT FROM `call_report` WHERE date(datetime) >= '$date1' AND date(datetime) <= '$date2'  ";
        if($uid != 0)
            $sql .= " AND eid = '$uid' ";
        if($usr != '0')
            $sql .= " AND eid IN ('".str_replace("a, "," ",$usr)."') ";
        if($current_company2 != 0 && $team == "")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('$team')) "; 
    
    if($types == 'c')
      $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_type = '$did')   ";
    elseif($types == 'q')
      $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_qualification = '$did')   ";
    elseif($types == 's')
      $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_speciality = '$did')   ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['COUNT'])? $rows['COUNT'] : 0;
  }



    function get_sample_by_doctor($item_id, $date1, $date2, $user_id, $team, $types, $cid, $hospital){
    global $conn, $current_company2, $loginuser;
    $sql = " SELECT SUM(d.qty) AS qty from demo_plot d, inventory i where d.item_id=i.id AND date(d.datetime) >= '$date1' AND date(d.datetime) <= '$date2' ";
    if($item_id != 0)
        $sql .= " AND d.item_id = '$item_id' ";
    
    if($types == 'c')
      $sql .= " AND d.uid IN(SELECT id FROM `doctor` WHERE doctor_type = '$cid')   ";
    elseif($types == 'q')
      $sql .= " AND d.uid IN(SELECT id FROM `doctor` WHERE doctor_qualification = '$cid')   ";
    elseif($types == 's')
      $sql .= " AND d.uid IN(SELECT id FROM `doctor` WHERE doctor_speciality = '$cid')   ";

    if($user_id != 'a')
      $sql .= " AND d.eid IN ('".str_replace("a, "," ",$user_id)."') ";
    if($en_user == 1){
          $sql .= "";
        }else{
          $sql .= $limituser78;
        }
    if($current_company2 != 0 && $team == "")
      $sql .= " AND d.eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "")
      $sql .= " AND d.eid IN (SELECT id  FROM employee WHERE distributor_id IN ('$team') ) ";
    if($hospital != "a")  
      $sql .= " AND d.uid IN (SELECT id FROM user WHERE company_name IN('".str_replace(", ", "','",str_replace("a, ","",$hospital))."'))";
    // echo $sql."<br>";  
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['qty'])? $rows['qty'] : 0;
  }



  function get_plans_by_doctor($uid, $did, $date1, $date2,  $types, $usr=0, $team=""){
    global $conn, $current_company2;
    $sql = " SELECT COUNT(id) AS COUNT FROM `work_plan` WHERE date(datetime) >= '$date1' AND date(datetime) <= '$date2' ";
        if($uid != 0)
            $sql .= " AND eid = '$uid' ";
        if($usr != '0')
            $sql .= " AND eid IN ('".str_replace("a, "," ",$usr)."') ";
         if($current_company2 != 0 && $team == "")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('$team')) ";
        
    if($types == 'c')
      $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_type = '$did')   ";
    elseif($types == 'q')
      $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_qualification = '$did')   ";
    elseif($types == 's')
      $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_speciality = '$did')   ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['COUNT'])? $rows['COUNT'] : 0;
  }



  function get_plans_by_date($did, $date, $user_id="a", $team="a"){
    global $conn, $current_company2;
    $sql = " SELECT COUNT(id) AS COUNT FROM `work_plan` WHERE date(datetime) = '$date' ";
    if($did != 0)
        $sql .= " AND eid = '$did' ";
    if($user_id != 'a')
        $sql.= " AND eid IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "a")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."')) ";    
    
  
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['COUNT'])? $rows['COUNT'] : 0;
  }




  function get_visits_by_month($did, $month, $year, $user_id="a", $team="a"){
    global $conn,$current_company2;
    $sql = " SELECT COUNT(id) AS COUNT FROM `call_report` WHERE month(datetime) = '$month' AND year(datetime) = '$year' ";
    if($did != 0)
        $sql .= " AND eid = '$did' ";
    if($user_id != 'a')
        $sql.= " AND eid IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "a")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."')) ";    
    
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['COUNT'])? $rows['COUNT'] : 0;
  }


  function get_plans_by_month($did, $month, $year, $user_id="a", $team="a"){
    global $conn,$current_company2;
    $sql = " SELECT COUNT(id) AS COUNT FROM `work_plan` WHERE month(datetime) = '$month' AND year(datetime) = '$year' ";
    if($did != 0)
       $sql .= " AND eid = '$did' ";
    if($user_id != 'a')
        $sql.= " AND eid IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "a")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."')) ";   
  
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['COUNT'])? $rows['COUNT'] : 0;
  }


function get_event_by_rep($rep_id, $date1, $date2, $event_type){
    global $conn;
    $sql = " SELECT count(id) AS id FROM `activity_type_report` WHERE date(datetime) >= '$date1' AND date(datetime) <= '$date2' AND activity_type = '$event_type' AND eid = '$rep_id' ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['id'])? $rows['id'] : 0;
  }

function get_expense_by_rep($rep_id, $date1, $date2, $expense_type){
    global $conn;
    $sql = " SELECT SUM(amount) AS amt FROM `marketing_expense` WHERE date(datetime) >= '$date1' AND date(datetime) <= '$date2' AND mexpense_type = '$expense_type' AND eid = '$rep_id' ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['amt'])? $rows['amt'] : 0;
  }

  function get_sample_by_month($item_id, $month, $year, $user_id, $team, $hospital){
    global $conn, $current_company2, $loginuser;
    $sql = " SELECT SUM(d.qty) AS qty from demo_plot d, inventory i where d.item_id=i.id AND month(d.datetime) = '$month' AND year(d.datetime) = '$year' ";
    if($item_id != 0)
        $sql .= " AND d.item_id = '$item_id' ";
    if($user_id != 'a')
      $sql .= " AND d.eid IN ('".str_replace("a, "," ",$user_id)."') ";
    if($en_user == 1){
          $sql .= "";
        }else{
          $sql .= $limituser78;
        }
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND d.eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
    elseif($team != "a")
      $sql .= " AND d.eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."') ) ";
    if($hospital != "a")  
      $sql .= " AND d.uid IN (SELECT id FROM user WHERE company_name IN('".str_replace(", ", "','",str_replace("a, ","",$hospital))."'))";
    //echo $sql."<br>";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return ($rows['qty'])? $rows['qty'] : 0;
  }

function get_demoplot_pogress_by_month($item_id, $month, $year, $user_id, $team){
    global $conn, $current_company2;
    $sql = " SELECT Count(id) AS count FROM demo_plot WHERE month(submit_date) = '$month' AND year(submit_date) = '$year' AND item_id = '$item_id' ";
    if($user_id != 'a')
        $sql .= " AND eid IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND eid IN (SELECT id  FROM employee WHERE  1=1  ) ";
    elseif($team != "a")
        $sql .= " AND eid IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."') ) ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return $rows['count'];
  }

function get_pogress_by_date($item_id, $date, $user_id, $team){
    global $conn, $current_company2;
    $sql = " SELECT Count(id) AS count FROM grower_fas_reporting WHERE date(datetime) = '$date' AND bayer_sol = '$item_id' ";
    if($user_id != 'a')
        $sql .= " AND emp_id IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND emp_id IN (SELECT id  FROM employee WHERE  1=1  ) ";
    elseif($team != "a")
        $sql .= " AND emp_id IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."') ) ";
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return $rows['count'];
  }

function get_pogress_by_month($item_id, $month, $year, $user_id, $team){
    global $conn, $current_company2;
    $sql = " SELECT Count(id) AS count FROM grower_fas_reporting WHERE month(datetime) = '$month' AND year(datetime) = '$year' AND bayer_sol = '$item_id' ";
    if($user_id != 'a')
        $sql .= " AND emp_id IN ('".str_replace("a,", "", $user_id)."') ";
    if($current_company2 != 0 && $team == "a")
      $sql .= " AND emp_id IN (SELECT id  FROM employee WHERE  1=1  ) ";
    elseif($team != "a")
        $sql .= " AND emp_id IN (SELECT id  FROM employee WHERE distributor_id IN ('".str_replace("a,", "", $team)."') ) "; 
    $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
    $rows = mysqli_fetch_array($res);
    return $rows['count'];
  }


function get_product_call_by_doctor($item_id, $user_id, $team, $grade, $date1, $date2, $types, $hospital){
        global $conn, $current_company2, $loginuser;
        $sql = " SELECT COUNT(cld.id) AS COUNT FROM `call_report` cl INNER JOIN callreport_doctor cld ON cl.id = cld.cid WHERE (cld.product1 = '$item_id' OR cld.product2 = '$item_id' OR cld.product3 = '$item_id') AND date(cl.datetime) >= '$date1' AND date(cl.datetime) <= '$date2' ";
        
        if($types == 'c')
            $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_type = '$grade')   ";
        elseif($types == 'q')
            $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_qualification = '$grade')   ";
        elseif($types == 's')
            $sql .= " AND uid IN(SELECT id FROM `doctor` WHERE doctor_speciality = '$grade')   ";
        
        if($user_id != 'a')
            $sql .= " AND cl.eid IN ('".str_replace("a,", "", $user_id)."' ) ";
        if($en_user == 1){
          $sql .= "";
        }else{
          $sql .= $limituser79;
        }
        if($current_company2 != 0 && $team == "")
            $sql .= " AND cl.eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
        elseif($team != "")
            $sql .= " AND cl.eid IN (SELECT id  FROM employee WHERE distributor_id IN ('$team') ) ";

        if($hospital != "a")    
            $sql .= " AND cl.uid IN (SELECT id FROM user WHERE company_name IN('".str_replace(", ", "','",str_replace("a, ","",$hospital))."'))";
        //echo $sql."<br>";
        $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
        $rows = mysqli_fetch_array($res);
        return ($rows['COUNT'])? $rows['COUNT'] : 0;
    }


function get_product_call_by_date($item_id, $date, $user_id, $team, $hospital){
        global $conn, $current_company2, $loginuser, $limituser61;
        $sql = " SELECT COUNT(cld.id) AS COUNT FROM `call_report` cl INNER JOIN callreport_doctor cld ON cl.id = cld.cid WHERE date(datetime) = '$date' $limituser61 ";
        if($item_id != 0)
            $sql .= " AND (cld.product1 = '$item_id' OR cld.product2 = '$item_id' OR cld.product3 = '$item_id') ";
        if($user_id != 'a')
            $sql .= " AND cl.eid IN ('".str_replace("a, "," ",$user_id)."') ";
        if($en_user == 1){
          $sql .= "";
        }else{
          $sql .= $limituser79;
        }
        if($current_company2 != 0 && $team == "a")
            $sql .= " AND cl.eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
        elseif($team != "a")
            $sql .= " AND cl.eid IN (SELECT id  FROM employee WHERE distributor_id IN (".str_replace("a, "," ",$team)." ))";
        if($hospital != "a")    
            $sql .= " AND cl.uid IN (SELECT id FROM user WHERE company_name IN('".str_replace(", ", "','",str_replace("a, ","",$hospital))."'))";
        $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
        $rows = mysqli_fetch_array($res);
        return ($rows['COUNT'])? $rows['COUNT'] : 0;
    }
    function get_product_call_by_month($item_id, $month, $year, $user_id, $team, $hospital){
        global $conn, $current_company2, $loginuser, $limituser61;
        $sql = " SELECT COUNT(cld.id) AS COUNT FROM `call_report` cl INNER JOIN callreport_doctor cld ON cl.id = cld.cid WHERE month(datetime) = '$month' AND year(datetime) = '$year' $limituser61 ";
        if($item_id != 0)
            $sql .= " AND (cld.product1 = '$item_id' OR cld.product2 = '$item_id' OR cld.product3 = '$item_id') ";
        if($user_id != 'a')
                $sql .= " AND cl.eid IN ('".str_replace("a, "," ",$user_id)."') ";
        if($en_user == 1){
          $sql .= "";
        }else{
          $sql .= $limituser79;
        }
        if($current_company2 != 0 && $team == "a")
            $sql .= " AND cl.eid IN (SELECT id  FROM employee WHERE  1=1 ) ";
        elseif($team != "a")
            $sql .= " AND cl.eid IN (SELECT id  FROM employee WHERE distributor_id IN (".str_replace("a, "," ",$team)." )) ";
        if($hospital != "a")    
            $sql .= " AND cl.uid IN (SELECT id FROM user WHERE company_name IN('".str_replace(", ", "','",str_replace("a, ","",$hospital))."'))";
        // echo $sql."<br>";
        $res = mysqli_query($conn, $sql)or die(mysqli_error($conn));
        $rows = mysqli_fetch_array($res);
        return ($rows['COUNT'])? $rows['COUNT'] : 0;
    }

  
 function numberTowords3($num)
{ 
$ones = array( 
1 => "one", 
2 => "two", 
3 => "three", 
4 => "four", 
5 => "five", 
6 => "six", 
7 => "seven", 
8 => "eight", 
9 => "nine", 
10 => "ten", 
11 => "eleven", 
12 => "twelve", 
13 => "thirteen", 
14 => "fourteen", 
15 => "fifteen", 
16 => "sixteen", 
17 => "seventeen", 
18 => "eighteen", 
19 => "nineteen" 
); 
$tens = array( 
1 => "ten",
2 => "twenty", 
3 => "thirty", 
4 => "forty", 
5 => "fifty", 
6 => "sixty", 
7 => "seventy", 
8 => "eighty", 
9 => "ninety" 
); 
$hundreds = array( 
"hundred and", 
"thousand", 
"million", 
"billion", 
"trillion", 
"quadrillion" 
); //limit t quadrillion 
$num = number_format($num,2,".",","); 
$num_arr = explode(".",$num); 
$wholenum = $num_arr[0]; 
$decnum = $num_arr[1]; 
$whole_arr = array_reverse(explode(",",$wholenum)); 
krsort($whole_arr); 
$rettxt = ""; 
foreach($whole_arr as $key => $i){ 
if($i < 20){ 
$rettxt .= $ones[$i]; 
}elseif($i < 100){ 
$rettxt .= $tens[substr($i,0,1)]; 
$rettxt .= " ".$ones[substr($i,1,1)]; 
}else{ 
$rettxt .= $ones[substr($i,0,1)]." ".$hundreds[0]; 
$rettxt .= " ".$tens[substr($i,1,1)]; 
$rettxt .= " ".$ones[substr($i,2,1)]; 
} 
if($key > 0){ 
$rettxt .= " ".$hundreds[$key]." "; 
} 
} 
if($decnum > 0){  
$rettxt .= " and "; 
if($decnum < 20){ 
$rettxt .= $ones[$decnum]; 
}elseif($decnum < 100){ 
$rettxt .= $tens[substr($decnum,0,1)]; 
$rettxt .= " ".$ones[substr($decnum,1,1)]; 
} 
} 
return $rettxt; 
} 
   
//  include('../email/sendtemail.php');
 
  // 
 

  function miniStat($conn, $bgColor, $icon, $query, $label) {
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);
    $count = reset($row); 
    $link = '';
    if($label === 'Total Leads' || $label === 'Today Leads' || $label === 'Active Leads'){
      $link = 'manage-lead.php';
    }else{
      $link = 'manage-followup.php';
    }
    $new_lable = set_link_label($label);
    echo "<a href='$link?$new_lable'>
      <div class='col-md-4'>
          <div class='mini-stat clearfix' style='background-color: #fff; padding: 12px 20px; border-radius: 10px; border: 1px solid #e2e6ea; display: flex; align-items: center; box-shadow: 0 4px 12px rgba(0,0,0,0.1);'>
              <span class='mini-stat-icon' style='background-color: $bgColor; color: white; padding: 12px; border-radius: 8px; margin-right: 20px; display: flex; justify-content: center; align-items: center;'>
                  <i class='$icon' style='font-size: 22px;'></i>
              </span>
              <div class='mini-stat-info' style='flex-grow: 1; color: #2c3e50; font-size: 14px;'>
                  <div style='font-size: 18px; font-weight: 700; color: #2c3e50; margin-bottom: 5px;'>$count</div>
                  <p style='font-size: 9px; color: #7f8c8d; text-transform: uppercase; margin: 0;'>$label</p>
              </div>
          </div>
      </div>
    </a>";
}

function set_link_label($link){

$label = '';
switch ($link) {
  case 'Total Leads':
   return $label = 'total';
    break;
  case 'Today Leads':
    $label = 'today';
    break;
  case 'Active Leads':
    $label = 'active';
    break;
  case 'Today Followup':
    $label = 'today';
    break;
  case 'Overdue Followups':
    $label = 'overdue';
    break;
  case 'Followups Not Completed':
    $label = 'not-completed'; 
    break;
  case 'Number of Followups Added Today':
    $label = 'added-today';
    break;
  case 'Completed Followups':
    $label = 'completed';
    break;
  default:
    $label = '';
    break;
}
return $label;
}
 
 //  Recheck if user is submitting form after shifting company from other tab
 
 
 $total_activeuser = mysqli_get_var(" Select count(id) from `employee` where id IN (Select id from `user` where inactive=0 && username!='' )  "); 
 
 
 if($info4000['snd_directcompany']==1) {
	
	$snd_so = 'sales';
	$snd_so_details = 'sales_details';
	
	 } else {
	$snd_so = 'so';
	$snd_so_details = 'so_details';	 
		 }
 

  function check_invoice_type($type_component)
  { 
      global $info1000,$info2000,$info3000;
          if($type_component==0){$invoice_type = $info1000['product_label']." Purchase";}
          elseif($type_component==1){$invoice_type = $info1000['material_label']." Purchase";}
          elseif($type_component==2){$invoice_type = $info2000['assets_label']." Purchase";}
          elseif($type_component==3){$invoice_type = $info3000['services_label']." Purchase";}
          else{$invoice_type = "-";}

      return $invoice_type; 
  } 

  function tax_amount_display($item_id, $tax_type, $tax_mrp, $tax_applied1, $tax_applied2, $tax_applied3, $sale_price, $mrp_price, $tax_return_all, $discount_percentage, $foc) {
        global $info3000;
    $baseAmount = ($tax_mrp == 1) ? $mrp_price : $sale_price;
    
    
    if ($tax_type == 0) {
        return $tax_return_all == 1 ? [0.0, 0.0, 0.0, 0.0] : [0.0];
    }
    
    if ($tax_type == 2) {
    } elseif ($tax_type == 3) {
        $discount_amount = ($baseAmount * $discount_percentage) / 100;
        $baseAmount -= $discount_amount;
    } elseif ($tax_type == 1) {
        if($info3000['inclusive_discount']==1) { 
            $discount_amount = ($baseAmount * $discount_percentage) / 100;
            $baseAmount = $baseAmount - $discount_amount;
        }
        
        $totalTaxPercent = $tax_applied1 + $tax_applied2 + $tax_applied3;
        $baseAmount = $baseAmount / (1 + ($totalTaxPercent / 100));
    }


    $tax1 = ($baseAmount * $tax_applied1) / 100;
    $tax2 = ($baseAmount * $tax_applied2) / 100;
    $tax3 = ($baseAmount * $tax_applied3) / 100;
    $totalTax = $tax1 + $tax2 + $tax3;

    if ($tax_return_all == 1) {
        return [round($tax1,2), round($tax2,2), round($tax3,2)];
    } else {
        return [round($totalTax,2)];
    }
}


// Hamza
function retailFBR($sid){
    global $conn, $info1000, $info2000, $info3000, $info4000;
     $discounted_amount = 0;
     if ($info1000['en_fbr'] == 1) {

        $TotalBillAmount = $TotalQuantity = $TotalSaleValue = $TotalTaxCharged = 0;
        $details_array   = array();
        $InvoiceType     = 3;
        $RefUSINValue    = null; // store the first found return USIN

        // ===== RETURN ITEMS =====
        $result = mysqli_query($conn, "SELECT * FROM sales_details WHERE order_id = '$sid' AND return_en = 1 ") or die(mysqli_error($conn));
       
        while ($myrow = mysqli_fetch_array($result)) {
            $InvoiceType = 3;
            $tax_applied = $myrow['tax_applied'];
            $myrow['qty'] = abs($myrow['qty']);
            
            $discounted_amount = $myrow['mrp_price'] / $myrow['discount'];
            if ($info2000['pos_tax_include'] == 1) {
                $TaxCharged = ($myrow['tp'] - ($myrow['tp'] / (1 + ($tax_applied / 100)))) * $myrow['qty'];
                $sale_value = ($myrow['tp'] * $myrow['qty']) - $TaxCharged;
            } else {
                $TaxCharged = (($myrow['tp'] * $tax_applied) / 100) * $myrow['qty'];
                $sale_value = ($myrow['tp'] * $myrow['qty']);
            }
            $TotalAmount = $sale_value + $TaxCharged;

            $TotalBillAmount += $TotalAmount;
            $TotalQuantity   += $myrow['qty'];
            $TotalSaleValue  += $sale_value;
            $TotalTaxCharged += $TaxCharged;
            
            $row_array = array(
                'ItemCode'     => $myrow['prd_id'],
                'ItemName'     => mysqli_get_var("SELECT name FROM inventory WHERE id = '".$myrow['prd_id']."' "),
                'Quantity'     => str_replace(",", "", number_format($myrow['qty'], 1)),
                'PCTCode'      => "11001010",
                'TaxRate'      => str_replace(",", "", number_format($tax_applied, 0)),
                'SaleValue'    => str_replace(",", "", number_format($sale_value, 0)),
                'TotalAmount'  => str_replace(",", "", number_format($TotalAmount, 0)),
                'TaxCharged'   => str_replace(",", "", number_format($TaxCharged, 0)),
                'Discount'     => number_format($discounted_amount, 1),
                'FurtherTax'   => number_format(0, 1),
                'InvoiceType'  => 3,
                'RefUSIN'      => $myrow['custom_field1']
            );
            $details_array[] = $row_array;

            if ($RefUSINValue === null && !empty($myrow['custom_field1'])) {
                $RefUSINValue = $myrow['custom_field1']; // take the first one only
            }
        }

        // ===== NORMAL SALE ITEMS =====
        $result = mysqli_query($conn, "SELECT * FROM sales_details WHERE order_id = '$sid' AND return_en = 0 ") or die(mysqli_error($conn));
        while ($myrow = mysqli_fetch_array($result)) {
            $InvoiceType = 1;
            $tax_applied = $myrow['tax_applied'];
            // $discounted_amount = $myrow['mrp_price'] / $myrow['discount'];
            $discounted_amount = (($myrow['mrp_price'] * $myrow['qty']) * (1 + $myrow['tax_applied'] / 100)) * ($myrow['discount'] / 100);
            if ($info2000['pos_tax_include'] == 1) {
                $TaxCharged = ($myrow['tp'] - ($myrow['tp'] / (1 + ($tax_applied / 100)))) * $myrow['qty'];
                $sale_value = ($myrow['tp'] * $myrow['qty']) - $TaxCharged;
            } else {
                $TaxCharged = (($myrow['tp'] * $tax_applied) / 100) * $myrow['qty'];
                $sale_value = ($myrow['tp'] * $myrow['qty']);
            }
            $TotalAmount = $sale_value + $TaxCharged - $discounted_amount;

            $TotalBillAmount += $TotalAmount;
            $TotalQuantity   += $myrow['qty'];
            $TotalSaleValue  += $sale_value;
            $TotalTaxCharged += $TaxCharged;

            $row_array = array(
                'ItemCode'     => $myrow['prd_id'],
                'ItemName'     => mysqli_get_var("SELECT name FROM inventory WHERE id = '".$myrow['prd_id']."' "),
                'Quantity'     => str_replace(",", "", number_format($myrow['qty'], 1)),
                'PCTCode'      => "11001010",
                'TaxRate'      => str_replace(",", "", number_format($tax_applied, 0)),
                'SaleValue'    => str_replace(",", "", number_format($sale_value, 0)),
                'TotalAmount'  => str_replace(",", "", number_format($TotalAmount, 0)),
                'TaxCharged'   => str_replace(",", "", number_format($TaxCharged, 0)),
                'Discount'     => number_format($discounted_amount, 1),
                'FurtherTax'   => number_format(0, 1),
                'InvoiceType'  => 1,
                'RefUSIN'      => null
            );
            $details_array[] = $row_array;
        }
         $TotalBillAmount = $TotalBillAmount + 1;
        // Final totals
        $TotalBillAmount = str_replace(",", "", number_format(abs($TotalBillAmount), 0));
        $TotalQuantity   = str_replace(",", "", number_format(abs($TotalQuantity), 0));
        $TotalSaleValue  = str_replace(",", "", number_format(abs($TotalSaleValue), 0));
        $TotalTaxCharged = str_replace(",", "", number_format(abs($TotalTaxCharged), 0));

        $details_array = json_encode($details_array);

        // Buyer details
        $bc_time = mysqli_get_var("SELECT datetime FROM sales WHERE id = '$sid'");
        $bname   = mysqli_get_var("SELECT name FROM sub_customer WHERE id IN (SELECT sub_customer FROM sales WHERE id = '$sid')");
        if ($bname == '') $bname = mysqli_get_var("SELECT company_name FROM user WHERE id IN (SELECT customer_id FROM sales WHERE id = '$sid')");
        if ($bname == '') $bname = "Buyer Name";

        $bntn = mysqli_get_var("SELECT ntn FROM sub_customer WHERE id IN (SELECT sub_customer FROM sales WHERE id = '$sid')");
        if ($bntn == '') $bntn = mysqli_get_var("SELECT ntn FROM customer WHERE id IN (SELECT customer_id FROM sales WHERE id = '$sid')");
        if ($bntn == '') $bntn = "1234567-8";

        $bcnic = mysqli_get_var("SELECT cnic FROM sub_customer WHERE id IN (SELECT sub_customer FROM sales WHERE id = '$sid')");
        if ($bcnic == '') $bcnic = mysqli_get_var("SELECT cnic FROM customer WHERE id IN (SELECT customer_id FROM sales WHERE id = '$sid')");
        if ($bcnic == '') $bcnic = "12345-1234567-8";

        // Proper RefUSIN JSON
        $RefUSINJson = $RefUSINValue ? '"'.addslashes($RefUSINValue).'"' : 'null';

        // ===== CURL REQUEST =====
        $curl = curl_init();
      
      $postData = array(
        "InvoiceNumber"    => "",
        "POSID"            => $info3000['pos_id'],
        "USIN"             => "USIN0",
        "DateTime"         => $bc_time,
        "BuyerNTN"         => $bntn,
        "BuyerCNIC"        => $bcnic,
        "BuyerName"        => $bname, // <-- apostrophe safe
        "BuyerPhoneNumber" => "0000-0000000",
        "TotalBillAmount"  => (float)$TotalBillAmount,
        "TotalQuantity"    => (int)$TotalQuantity,
        "TotalSaleValue"   => (float)$TotalSaleValue,
        "TotalTaxCharged"  => (float)$TotalTaxCharged,
        "Discount"         => (float)$discounted_amount,
        "FurtherTax"       => 0.0,
        "PaymentMode"      => 1,
        "RefUSIN"          => $RefUSINJson,
        "InvoiceType"      => $InvoiceType,
        "Items"            => json_decode($details_array, true), // if already JSON string
    );

    curl_setopt_array($curl, array(
        CURLOPT_URL            => $info3000['fbr_link'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => '',
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => json_encode($postData),
        CURLOPT_HTTPHEADER     => array(
            'Content-Type: application/json',
            'Authorization: Bearer 1298b5eb-b252-3d97-8622-a4a69d5bf818'
        ),
    ));


        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response);

        if ($response->Code == 100) {
            $InvoiceNumber = $response->InvoiceNumber;
            mysqli_get_var("UPDATE sales SET fbr_InvoiceNumber = '$InvoiceNumber' WHERE id = '$sid'");
        }
  }
}


// Hamza end



function fetch_row_prepared($conn, $sql, $types = "", $params = []) 
{
    $stmt = $conn->prepare($sql);
    if ($stmt === false) return false;
    if (!empty($types) && !empty($params)) 
    {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : false;
    $stmt->close();
    return $row;
}

function status_html($ok) 
{
    return $ok ? "<span style='color:green;font-weight:bold'>OK</span>" : "<span style='color:red;font-weight:bold'>FAIL</span>";
}

function sendFBRInvoice($sid) 
{
    global $conn, $info1000, $info2000, $info3000, $info4000;

    $salesQuery = mysqli_query($conn, "SELECT * FROM sales WHERE id = '$sid'");
    $salesData = mysqli_fetch_assoc($salesQuery);

    if(!$salesData) {
        return ["error" => true, "message" => "Sales invoice not found"];
    }

    $sales_customer = mysqli_query($conn, "SELECT * FROM customer WHERE id = ".$salesData['customer_id']);
    $sales_customer_data = mysqli_fetch_assoc($sales_customer);

    $sales_user = mysqli_query($conn, "SELECT * FROM user WHERE id = ".$salesData['customer_id']);
    $sales_user_data = mysqli_fetch_assoc($sales_user);

    // $buyerNTNCNIC = !empty($sales_customer_data['ntn']) ? $sales_customer_data['ntn'] : "0000000000000";
    $buyerNTNCNIC = !empty($sales_customer_data['ntn']) 
    ? substr($sales_customer_data['ntn'], 0, 7) 
    : "0000000";

    $buyerRegistrationType = ($sales_customer_data['filer'] == 1) ? "Registered" : "Unregistered";
    $buyerBusinessName = !empty($sales_user_data['company_name']) ? $sales_user_data['company_name'] : "Customer Name";
    $buyerAddress = !empty($sales_user_data['address']) ? $sales_user_data['address'] : "Buyer Address";

    $buyerstate = $sales_user_data['state'];
    $buyerProvince = mysqli_get_var("SELECT name FROM states_dir WHERE id = '$buyerstate'");
    $buyerProvince = !empty($buyerProvince) ? $buyerProvince : "";

    $scenarioId = !empty($salesData['fbr_scenario']) ? (int)$salesData['fbr_scenario'] : 1;
    $scenarioData = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name, description FROM fbr_scenario WHERE id = '$scenarioId'"));

    $scenarioName = $scenarioData['name'] ?? "SN001";
    $scenarioDescription = $scenarioData['description'] ?? "Goods at Standard Rate (default)";

    $itemsQuery = mysqli_query($conn, "SELECT * FROM sales_details WHERE order_id = '$sid'");
    $fbrItems = [];

    while ($row = mysqli_fetch_assoc($itemsQuery)) 
    {
        $productDescription = mysqli_get_var("SELECT name FROM inventory WHERE id = ".$row['prd_id']);
        $hsCode = mysqli_get_var("SELECT hs_code FROM inventory WHERE id = ".$row['prd_id']);
        $unit_id = mysqli_get_var("SELECT unit FROM inventory WHERE id = ".$row['prd_id']);
        $weight = mysqli_get_var("SELECT weight FROM inventory WHERE id = ".$row['prd_id']);
        $unit_name = mysqli_get_var("SELECT name FROM product_unit WHERE id = ".$unit_id);

        $productDescription = !empty($productDescription) ? $productDescription : "Product Description";
        $hsCode = !empty($hsCode) ? $hsCode : "0101.2100";
        $unit_name = !empty($unit_name) ? $unit_name : "Numbers, pieces, units";

        // -------------------------
        // START tax/discount logic
        // -------------------------
        $tax_type   = $row['tax_type']; // 0=No Tax,1=Inclusive,2=Before Disc,3=After Disc
        $tax_on_mrp = $row['tax_mrp'];  // 1=MRP, 0=TP

        $price = ($tax_on_mrp == 1) ? $row['mrp_price'] : $row['tp'];
        if ($scenarioName === "SN008") 
        {
            $price = $row['tp']*$row['qty'];
        } 
        else
        {
            $price = ($tax_on_mrp == 1) ? $row['mrp_price'] : $row['tp'];
        }
        
        if ($scenarioName === "SN008") 
        {
            $notifiedprice = ($tax_on_mrp == 1) ? $row['mrp_price'] : $row['tp'];
            $notifiedprice = $notifiedprice * $row['qty'];
        } 
        else
        {
            $notifiedprice = 0;
        }
        
        
        
        $qty   = $row['qty'];
        $gross_amount = $row['tp']*$row['qty'];
        $focgross_amount = ($row['tp']*$row['qty']) + $row['foc'];

        // discounts
        $disc1_amount = $gross_amount * ($row['discount']/100);
        $amount_after_disc1 = $gross_amount - $disc1_amount;

        $disc2_amount = $amount_after_disc1 * ($row['discount2']/100);
        $amount_after_disc2 = $amount_after_disc1 - $disc2_amount;

        $disc3_amount = $row['discount3'] * $qty;
        $amount_after_disc3 = $amount_after_disc2 - $disc3_amount;

        $total_discount = $disc1_amount + $disc2_amount + $disc3_amount;

        // taxes
        $tax1_amount = 0; $tax2_amount = 0; $tax3_amount = 0; $net_amount = 0;
        $base_amount_for_tax = $amount_after_disc3; // default

        if ($tax_type == 1) {
            // Inclusive
            $net_amount = $gross_amount;
            $base_amount_for_tax = $gross_amount;
        } elseif ($tax_type == 2) {
            // Before Discount (apply tax on gross/focgross)
            $tax1_amount = $focgross_amount * ($row['tax_applied']/100);
            $tax3_amount = $amount_after_disc3 * ($row['tax_applied3']/100);
            $tax2_amount = ($amount_after_disc3 + $tax1_amount + $tax3_amount) * ($row['tax_applied2']/100);
            $net_amount  = $amount_after_disc3 + $tax1_amount + $tax2_amount + $tax3_amount;
            $base_amount_for_tax = $focgross_amount;
        } elseif ($tax_type == 3) {
            // After Discount
            $tax1_amount = $amount_after_disc3 * ($row['tax_applied']/100);
            $tax3_amount = $amount_after_disc3 * ($row['tax_applied3']/100);
            $tax2_amount = ($amount_after_disc3 + $tax1_amount + $tax3_amount) * ($row['tax_applied2']/100);
            $net_amount  = $amount_after_disc3 + $tax1_amount + $tax2_amount + $tax3_amount;
            $base_amount_for_tax = $amount_after_disc3;
        } else {
            // No Tax
            $net_amount = $amount_after_disc3;
            $base_amount_for_tax = $amount_after_disc3;
        }
        
        if ($scenarioName === "SN008") 
        {
            $sales_value = $row['tp']*$row['qty'];
        } 
        else
        {
            $sales_value = $base_amount_for_tax;
        }
        
        // -------------------------
        // END tax/discount logic
        // -------------------------

        $sroScheduleNo = "";
        $sroItemSerialNo = "";
        
        if ($scenarioName === "SN005" || $scenarioName === "SN006") {
            $sroScheduleNo = "6th Schd Table I";
            $sroItemSerialNo = "100";
        } 
        if ($scenarioName === "SN018" || $scenarioName === "SN019") 
        {
            if ($row['tax_applied'] == 16) 
            {
                $sroScheduleNo = "Sixth Schedule Table II";
                $sroItemSerialNo = "11"; 
            }
        
            if ($row['tax_applied'] == 5) 
            {
                $sroScheduleNo = "SRO 781(I)/2018";
                $sroItemSerialNo = "3"; 
            }
        } 
        if ($scenarioName === "SN024") 
        {
            $sroScheduleNo = "297(I)/2023-Table-I";
            $sroItemSerialNo = "12";
        }  
        if($info3000['sendweight_fbr'] == 1)
        {
            if($weight == '' || $weight == 0 || $weight == '0')
            {
                $actual_weight = $row['qty'];
            }
            else
            {
                $actual_weight = $row['qty'] * $weight; 
            }
        }
        else
        {
            $actual_weight = $row['qty'];
        }

        if($info3000['en_customdailyid']==1)
        {
            $invRef = $salesData['daily_id'];
        } 
        else
        {
            $invRef = $sid;
        }

        $fbrItems[] = [
            "hsCode" => $hsCode,
            "productDescription" => $productDescription,
            "rate" => ($scenarioId == 5 || $scenarioId == 6) ? "Exempt" : round($row['tax_applied'], 2)."%", 
            "uoM" => $unit_name,
            "quantity" => round($actual_weight, 4),
            "totalValues" => round($row['prd_amount'], 2),
            "valueSalesExcludingST" => round($sales_value, 2),  // FBR base value
            "fixedNotifiedValueOrRetailPrice" => round($notifiedprice, 2),
            "salesTaxApplicable" => round($tax1_amount, 2),
            "salesTaxWithheldAtSource" => 0,
            "extraTax" => 0,
            "furtherTax" => round($tax3_amount, 2),
            "sroScheduleNo" => $sroScheduleNo,
            "fedPayable" => 0,
            "discount" => round($total_discount, 2),
            "saleType" => $scenarioDescription, 
            "sroItemSerialNo" => $sroItemSerialNo
        ];
    }

    $fbrInvoice = [
        "invoiceType" => "Sale Invoice",
        "invoiceDate" => date("Y-m-d", strtotime($salesData['datetime'])),
        "sellerNTNCNIC" => $info4000['sellerNTNCNIC'],
        "sellerBusinessName" => $info4000['sellerBusinessName'],
        "sellerProvince" => $info4000['sellerProvince'],
        "sellerAddress" => $info4000['sellerAddress'],
        "buyerNTNCNIC" => $buyerNTNCNIC,
        "buyerBusinessName" => $buyerBusinessName,
        "buyerProvince" => $buyerProvince,
        "buyerAddress" => $buyerAddress,
        "invoiceRefNo" => "$invRef",
        "buyerRegistrationType" => $buyerRegistrationType,
        "scenarioId" => $scenarioName,
        "items" => $fbrItems
    ];

    $fbrApiUrl = ($info4000['active_production_eInvoice']==1) 
        ? "https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata"
        : "https://gw.fbr.gov.pk/di_data/v1/di/postinvoicedata_sb";

    $token = ($info4000['active_production_eInvoice']==1) 
        ? $info4000['production_accessToken']
        : $info4000['sandbox_accessToken'];

    $jsonPayload = json_encode($fbrInvoice);

    if(1==1)
    {
        $payloadDir = __DIR__ . "/sales"; 
        
        if (!is_dir($payloadDir)) {
            mkdir($payloadDir, 0777, true);
        }
        
        $payloadFilePath = $payloadDir . "/fbr_payload_" . $sid . "_" . date('Ymd_His') . ".json";
        
        if (file_put_contents($payloadFilePath, $jsonPayload) === false) {
            error_log("Failed to write FBR payload file: " . $payloadFilePath);
        } else {
            error_log("FBR payload saved to: " . $payloadFilePath);
        }
    }

    $ch = curl_init($fbrApiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
        'Accept: application/json',
        'Accept-Encoding: gzip, deflate, br',
        'Connection: keep-alive',
        'User-Agent: PostmanRuntime/7.44.1'
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) 
    {
        $apiResponse = json_decode($response, true);
        $statusCode = isset($apiResponse['validationResponse']['statusCode']) 
    ? $apiResponse['validationResponse']['statusCode'] 
    : '';

$invoiceNo = isset($apiResponse['validationResponse']['invoiceStatuses'][0]['invoiceNo']) 
    ? $apiResponse['validationResponse']['invoiceStatuses'][0]['invoiceNo'] 
    : '';

$e_status = isset($apiResponse['validationResponse']['invoiceStatuses'][0]['status']) 
    ? $apiResponse['validationResponse']['invoiceStatuses'][0]['status'] 
    : '';

        if($statusCode=="00" && $invoiceNo)
        {
            mysqli_query($conn, "UPDATE sales SET 
                fbr_irn = '$invoiceNo',
                fbr_status = '$e_status',
                fbr_response_json = '".mysqli_real_escape_string($conn, $response)."'
                WHERE id = '$sid'");
            return ["error"=>false, "message"=>"Invoice Posted Successfully", "invoiceNo"=>$invoiceNo];
        } 
        else 
        {
            mysqli_query($conn, "UPDATE sales SET 
                fbr_response_json = '".mysqli_real_escape_string($conn, $response)."'
                WHERE id = '$sid'");
            return ["error"=>true, "message"=>"FBR Response Error", "response"=>$apiResponse];
        }
    } 
    else 
    {
        mysqli_query($conn, "UPDATE sales SET 
            fbr_status = '$httpCode',
            fbr_response_json = '".mysqli_real_escape_string($conn, $response)."'
            WHERE id = '$sid'");
        return ["error"=>true, "message"=>"HTTP Error: $httpCode", "response"=>$response];
    }
}

function tableExists($conn, $table) {
    $res = mysqli_query($conn, "SHOW TABLES LIKE '$table'");
    return mysqli_num_rows($res) > 0;
}

function display_tax_values($item_id, $discount1, $discount2, $discount3, $discount4, $discount5, $tax1, $tax2, $tax3, $tax_category, $tax_type, $mode, $tp_price, $mrp_price, $qty) {
    // Step 1: Gross
    $gross = $tp_price * $qty;

    // Step 2: Base Val
    $base_price = ($tax_category == 1) ? $mrp_price * $qty : $tp_price * $qty;

    // Step 3: Tax Calculation
    if ($tax_type == 0 || $tax_type == 1) {
        // No Tax or Inclusive Tax
        return 0;
    }

    // ---------- Scenario 3: Tax Before Discount ----------
    if ($tax_type == 2) {
        $tax_amount1 = $base_price * ($tax1 / 100);
        $value_after_tax1 = $base_price + $tax_amount1;

        $tax_amount2 = $value_after_tax1 * ($tax2 / 100);
        $value_after_tax2 = $value_after_tax1 + $tax_amount2;

        $tax_amount3 = $value_after_tax2 * ($tax3 / 100);

        // Return based on mode
        if ($mode == 1) return round($tax_amount1, 2);
        if ($mode == 2) return round($tax_amount2, 2);
        if ($mode == 3) return round($tax_amount3, 2);

        return round($tax_amount1 + $tax_amount2 + $tax_amount3, 2);
    }

    // ---------- Scenario 4: Tax After Discount ----------
    if ($tax_type == 3) {
        // Apply percentage discounts
        $net = $gross;
        $net -= $discount1;
        $net -= $discount2;
        $net -= $discount3; // Flat Rs
        $net -= $net * ($discount4 / 100);
        $net -= $net * ($discount5 / 100);

        // Apply taxes on discounted price
        $tax_amount1 = $net * ($tax1 / 100);
        $value_after_tax1 = $net + $tax_amount1;

        $tax_amount2 = $value_after_tax1 * ($tax2 / 100);
        $value_after_tax2 = $value_after_tax1 + $tax_amount2;

        $tax_amount3 = $value_after_tax2 * ($tax3 / 100);

        // Return based on mode
        if ($mode == 1) return round($tax_amount1, 2);
        if ($mode == 2) return round($tax_amount2, 2);
        if ($mode == 3) return round($tax_amount3, 2);

        return round($tax_amount1 + $tax_amount2 + $tax_amount3, 2);
    }

    return 0; 
}

$cogs_inventoryaccountid   = $info3000['cogs_inventoryaccountid'];


$greeting_time = date("H"); // 00 to 23

$greeting = "";
if ($greeting_time < 12) {
    $greeting = "Good Morning";
} elseif ($greeting_time < 17) {
    $greeting = "Good Afternoon";
} elseif ($greeting_time < 20) {
    $greeting = "Good Evening";
} else {
    $greeting = "Good Night";
}

