Overview
  • Package
  • Class
  • Tree
  • Deprecated
  • Todo
  • Hook Reference
  • Docs Home

Packages

  • BKAP
    • Addons
    • Admin-Bookings
    • Attribute-Lockout
    • Block-Pricing
    • Booking-Box
    • Booking-Confirmation
    • Booking-Process
    • Cancel-Order
    • Cart
    • Checkout-Process
    • Core
    • Date-Time
    • Emails
    • Functions
    • Global-Function
    • Global-Settings
    • Google-Calendar-Sync
    • ICS
    • Import-Booking
    • Labels
    • License
    • Menus
    • Meta-Boxes
    • Reschedule
    • Resources
    • Search-Widget
    • Special-Price
    • Uninstall
    • Validation
    • Variation-Lockout
    • Vendors
      • Dokan
      • WC-Vendors
    • View-Bookings
  • None

Classes

  • bkap_addon_compatibility_class
  • bkap_admin_bookings
  • bkap_approve_booking
  • bkap_attributes
  • bkap_block_booking
  • BKAP_Booking
  • bkap_booking_box_class
  • bkap_booking_confirmation
  • bkap_booking_process
  • BKAP_Bookings_View
  • bkap_calendar_sync
  • bkap_cancel_order
  • bkap_cart
  • bkap_checkout
  • bkap_common
  • BKAP_Customer_Meta_Box
  • BKAP_Details_Meta_Box
  • bkap_dokan_calendar_class
  • bkap_dokan_class
  • bkap_dokan_orders_class
  • bkap_dokan_products_class
  • bkap_edit_bookings_class
  • BKAP_Email_Booking_Cancelled
  • BKAP_Email_Booking_Confirmed
  • BKAP_Email_Booking_Rescheduled_Admin
  • BKAP_Email_Imported_Event
  • BKAP_Email_Manager
  • BKAP_Email_New_Booking
  • BKAP_Gcal
  • BKAP_Gcal_Event
  • bkap_gcal_sync_settings
  • bkap_global_settings
  • BKAP_Google_Events_View
  • bkap_ics
  • bkap_license
  • bkap_load_scripts_class
  • BKAP_OPC_Addon
  • BKAP_Payment_Gateway
  • BKAP_Product_Resource
  • bkap_rescheduled_order_class
  • BKAP_Resource_Details_Meta_Box
  • BKAP_Save_Meta_Box
  • bkap_special_booking_price
  • bkap_timeslot_price
  • bkap_validation
  • bkap_variations
  • BKAP_Vendors
  • bkap_wc_vendors
  • bkap_wcv_product
  • Booking_Information_In_Voucher_Template
  • Class_Bkap_Product_Resource
  • Custom_WooCommerce_Widget_Product_Search
  • EDD_BOOK_Plugin_Updater
  • global_menu
  • import_bookings
  • product_gcal_settings
  • view_bookings
  • WAPBK_Import_Bookings_Table
  • WAPBK_View_Bookings_Table
  • woocommerce_booking

Functions

  • addDayswithdate
  • bkap_400_create_meta
  • bkap_400_recurring_data
  • bkap_400_update_db_tab
  • bkap_400_update_enable_specific
  • bkap_400_update_enable_week_blocking
  • bkap_400_update_holidays
  • bkap_400_update_ranges
  • bkap_400_update_recurring_lockout
  • bkap_400_update_settings
  • bkap_400_update_special
  • bkap_400_update_specific
  • bkap_410_create_meta
  • bkap_410_update_block_pricing_option_values_in_new_way
  • bkap_410_update_fixed_blocks
  • bkap_410_update_price_ranges
  • bkap_410_update_settings
  • bkap_420_add_gcal_posts
  • bkap_420_add_gcal_tour_posts
  • bkap_420_gcal_batch_size
  • bkap_420_gcal_meta
  • bkap_420_update_settings
  • bkap_add_days_to_date
  • bkap_array_of_given_date_range
  • bkap_booked_resources
  • bkap_booking_posts_for_resource
  • bkap_calculate_bookings_for_resource
  • bkap_check_booking_available
  • bkap_check_day_booking_available
  • bkap_check_for_max_date
  • bkap_check_for_min_date
  • bkap_check_holiday
  • bkap_check_in_custom_holiday_range
  • bkap_check_resource_available
  • bkap_check_resource_booked_in_date_range
  • bkap_db_420_1
  • bkap_db_420_2
  • bkap_delete_event_from_gcal
  • bkap_delete_folder_and_files
  • bkap_delete_options
  • bkap_delete_tables
  • bkap_find_matching_product_variation
  • bkap_generate_bookable_data
  • bkap_get_book_arrays
  • bkap_get_book_t
  • bkap_get_booked
  • bkap_get_booked_checkout
  • bkap_get_custom_posts
  • bkap_get_dateToCal
  • bkap_get_day_between_Week
  • bkap_get_db_count
  • bkap_get_escapeString
  • bkap_get_lockout
  • bkap_get_month_range
  • bkap_get_post_meta
  • bkap_get_posted_availability
  • bkap_get_total_timeslot_maximum_booking
  • bkap_get_week_range
  • bkap_import_events_cron
  • bkap_insert_event_to_gcal
  • bkap_manual_db_update_v420
  • bkap_orderby_date_key
  • bkap_save_resources
  • bkap_sort_by_from_time
  • bkap_update_po_file
  • bkap_vendors_get_bookings
  • bkap_widgets_init
  • bkapSortByPriority
  • calback_bkap_max_date
  • check_in_fixed_block_booking
  • check_in_range
  • check_in_range_abp
  • check_in_range_holidays
  • check_in_range_weekdays
  • create_posts
  • get_availability_for_date
  • get_booked_multiple
  • get_bookings_for_date
  • get_bookings_for_range
  • get_date_lockout
  • get_slot_availability
  • get_slot_lockout
  • get_standard_decimal_thousand_separator_price
  • is_booking_active
  • woocommerce_bkap_add_cron_schedule
   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  101  102  103  104  105  106  107  108  109  110  111  112  113  114  115  116  117  118  119  120  121  122  123  124  125  126  127  128  129  130  131  132  133  134  135  136  137  138  139  140  141  142  143  144  145  146  147  148  149  150  151  152  153  154  155  156  157  158  159  160  161  162  163  164  165  166  167  168  169  170  171  172  173  174  175  176  177  178  179  180  181  182  183  184  185  186  187  188  189  190  191  192  193  194  195  196  197  198  199  200  201  202  203  204  205  206  207  208  209  210  211  212  213  214  215  216  217  218  219  220  221  222  223  224  225  226  227  228  229  230  231  232  233  234  235  236  237  238  239  240  241  242  243  244  245  246  247  248  249  250  251  252  253  254  255  256  257  258  259  260  261  262  263  264  265  266  267  268  269  270  271  272  273  274  275  276  277  278  279  280  281  282  283  284  285  286  287  288  289  290  291  292  293  294  295  296  297  298  299  300  301  302  303  304  305  306  307  308  309  310  311  312  313  314  315  316  317  318  319  320  321  322  323  324  325  326  327  328  329  330  331  332  333  334  335  336  337  338  339  340  341  342  343  344  345  346  347  348  349  350  351  352  353  354  355  356  357  358  359  360  361  362  363  364  365  366  367  368  369  370  371  372  373  374  375  376  377  378  379  380  381  382  383  384  385  386  387  388  389  390  391  392  393  394  395  396  397  398  399  400  401  402  403  404  405  406  407  408  409  410  411  412  413  414  415  416  417  418  419  420  421  422  423  424  425  426  427  428  429  430  431  432  433  434  435  436  437  438  439  440  441  442  443  444  445  446  447  448  449  450  451  452  453  454  455  456  457  458  459  460  461  462  463  464  465  466  467  468  469  470  471  472  473  474  475  476  477  478  479  480  481  482  483  484  485  486  487  488  489  490  491  492  493  494  495  496  497  498  499  500  501  502  503  504  505  506  507  508  509  510  511  512  513  514  515  516  517  518  519  520  521  522  523  524  525  526  527  528  529  530  531  532  533  534  535  536  537  538  539  540  541  542  543  544  545  546  547  548  549  550  551  552  553  554  555  556  557  558  559  560  561  562  563  564  565  566  567  568  569  570  571  572  573  574  575  576  577  578  579  580  581  582  583  584  585  586  587  588  589  590  591  592  593  594  595  596  597  598  599  600  601  602  603  604  605  606  607  608  609  610  611  612  613  614  615  616  617  618  619  620  621  622  623  624  625  626  627  628  629  630  631  632  633  634  635  636  637  638  639  640  641  642  643  644  645  646  647  648  649  650  651  652  653  654  655  656  657  658  659  660  661  662  663  664  665  666  667  668  669  670  671  672  673  674  675  676  677  678  679  680  681  682  683  684  685  686  687  688  689  690  691  692  693  694  695  696  697  698  699  700  701  702  703  704  705  706  707  708  709  710  711  712  713  714  715  716  717  718  719  720  721  722  723  724  725  726  727  728  729  730  731  732  733  734  735  736  737  738  739  740  741  742  743  744  745  746  747  748  749  750  751  752  753  754  755  756  757  758  759  760  761  762  763  764  765  766  767  768  769  770  771  772  773  774  775  776  777  778  779  780  781  782  783  784  785  786  787  788  789  790  791  792  793  794  795  796  797  798  799  800  801  802  803  804  805  806  807  808  809  810  811  812  813  814  815  816  817  818  819  820  821  822  823  824  825  826  827  828  829  830  831  832  833  834  835  836  837  838  839  840  841  842  843  844  845  846  847  848  849  850  851  852  853  854  855  856  857  858  859  860  861  862  863  864  865  866  867  868  869  870  871  872  873  874  875  876  877  878  879  880  881  882  883  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931  932  933  934  935  936  937  938  939  940  941  942  943  944  945  946  947  948  949  950  951  952  953  954  955  956  957  958  959  960  961  962  963  964  965  966  967  968  969  970  971  972  973  974  975  976  977  978  979  980  981  982  983  984  985  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 
<?php
/**
 * Bookings and Appointment Plugin for WooCommerce
 *
 * Contains functions to run DB Upgrades.
 *
 * @author   Tyche Softwares
 * @package  BKAP/Functions
 * @category Classes
 */

/**
 * Database update tab. Displayed only when automatic update fails.
 *
 * @since 4.0.0
 */

function bkap_400_update_db_tab() {
    ?>
    <form method="post">
    <h2><?php _e( 'DB Update for Booking & Appointment Plugin', 'woocommerce-booking' ); ?></h2>
    <?php 
    // re-confirm the db update status
    $db_status = get_option( 'bkap_400_update_db_status' );
    
    $db_status_410 = get_option( 'bkap_410_update_db_status' );

    $message = "";
     
    $plugin_version = get_option( 'woocommerce_booking_db_version' );
     
    $valid_status = array( 'fail', 'success' );

    // Add GCAL meta
    $gcal_meta_update = get_option( 'bkap_420_update_gcal_meta' );
    if ( $gcal_meta_update === null ) {
        bkap_420_gcal_meta();
    }

    if ( ! empty( $_POST[ 'bkap_420_1' ] ) || isset( $_GET[ 'loop_next_view' ] ) ) {
        $number_of_batches = bkap_get_db_count();

        if ( isset( $_GET[ 'batch' ] ) && $_GET[ 'batch' ] != 0 ) {
            $loop = $_GET[ 'batch' ];
            $loop = (int)$loop;
        }else{
            $loop = 1;
        }
        
        if ( $loop <= $number_of_batches ){
            $_status = bkap_db_420_1( $loop );

            $status_percent = round( ( ( $loop * 100 ) / $number_of_batches ), 0 );
            // add the progress
            ?>
                <style type="text/css">
                    #bkap_update_progress {
                        width: 100%;
                        background-color: grey;
                    }

                    #bkap_progress_bar {
                        width: <?php echo $status_percent;?>%;
                        height: 30px;
                        background-color: #0085ba;
                        text-align: center;
                        line-height: 30px;
                        color: white; 
                    }
                </style>
                <div id="bkap_update_progress">
                    <div id="bkap_progress_bar"><?php echo $status_percent;?>%</div>
                </div>
            <?php
                
            $loop = $loop + 1;
            // reload the page so the progress can be displayed                
            $args = array( 'post_type' => $_REQUEST[ 'post_type' ],
                        'page' => $_REQUEST[ 'page' ],
                        'action' => $_REQUEST[ 'action' ],
                        'batch' => $loop,
                        'loop_next_view' => 'true',
             );

            $redirect_url = add_query_arg( $args, get_admin_url() . 'edit.php' );

            ?>
                <script type="text/javascript">
                    window.location.href = "<?php echo $redirect_url;?>";
                </script>
            <?php
        }else {
            $bkap_view_status = 'success';
            $bkap_view_update_stat = get_option( 'bkap_420_update_stats' );
            if ( isset( $bkap_view_update_stat ) && count( $bkap_view_update_stat ) > 0 && is_array( $bkap_view_update_stat ) ) {
                foreach ( $bkap_view_update_stat as $stat_key => $stat_value ) {
                    if ( isset( $stat_value['failed_count'] ) && $stat_value['failed_count'] > 0 ) {
                        $bkap_view_status = 'fail';
                        break;
                    }
                }
            }
            if ( $bkap_view_status === 'success' ) {
                update_option( 'bkap_420_update_db_status', 'success' );
            }else if ( $bkap_view_status === 'fail' ) {
                update_option( 'bkap_420_update_db_status', 'fail' );
            }
        }
        
    }

    if ( ! empty( $_POST[ 'bkap_420_2' ] ) || isset( $_GET[ 'loop_next' ] ) ) {
        $number_of_batches = bkap_420_gcal_batch_size();

        if ( isset( $_GET[ 'batch_gcal' ] ) && $_GET[ 'batch_gcal' ] != 0 ) {
            $loop = $_GET[ 'batch_gcal' ];
            $loop = (int)$loop;
        }else{
            $loop = 1;
        }
        
        if ( $loop <= $number_of_batches ){
            $_status = bkap_db_420_2( $loop );
        

            $status_percent = round( ( ( $loop * 100 ) / $number_of_batches ), 0 );
            // add the progress
            ?>
                <style type="text/css">
                    #bkap_update_progress {
                        width: 100%;
                        background-color: grey;
                    }

                    #bkap_progress_bar {
                        width: <?php echo $status_percent;?>%;
                        height: 30px;
                        background-color: #0085ba;
                        text-align: center;
                        line-height: 30px;
                        color: white; 
                    }
                </style>
                <div id="bkap_update_progress">
                    <div id="bkap_progress_bar"><?php echo $status_percent;?>%</div>
                </div>
            <?php
                
            $loop = $loop + 1;
            // reload the page so the progress can be displayed                
            $args = array( 'post_type' => $_REQUEST[ 'post_type' ],
                        'page' => $_REQUEST[ 'page' ],
                        'action' => $_REQUEST[ 'action' ],
                        'batch_gcal' => $loop,
                        'loop_next' => 'true',
             );
            //wp_safe_redirect( add_query_arg( $args, get_admin_url() . 'edit.php' ) );

            $redirect_url = add_query_arg( $args, get_admin_url() . 'edit.php' );

            ?>
                <script type="text/javascript">
                    window.location.href = "<?php echo $redirect_url;?>";
                </script>
            <?php 
        }else {
            $bkap_gcal_status = 'success';
            $bkap_gcal_update_stat = get_option( 'bkap_420_gcal_update_stats' );
            if ( isset( $bkap_gcal_update_stat ) && count( $bkap_gcal_update_stat ) > 0 && is_array( $bkap_gcal_update_stat ) ) {
                foreach ( $bkap_gcal_update_stat as $stat_key => $stat_value ) {
                    if ( isset( $stat_value['failed_count'] ) && $stat_value['failed_count'] > 0 ) {
                        $bkap_gcal_status = 'fail';
                        break;
                    }
                }
            }
            if ( $bkap_gcal_status === 'success' ) {
                update_option( 'bkap_420_update_gcal_status', 'success' );
            }else if ( $bkap_gcal_status === 'fail' ) {
                update_option( 'bkap_420_update_gcal_status', 'fail' );
            }
        }
        
    }    
    
    $db_status_420 = get_option( 'bkap_420_update_db_status' );
    
    $gcal_status_420 = get_option( 'bkap_420_update_gcal_status' );

    if ( isset( $plugin_version ) && '4.1.0' <= $plugin_version &&
        isset( $db_status_420 ) && !in_array( $db_status_420, $valid_status ) &&
        isset( $gcal_status_420 ) && !in_array( $gcal_status_420, $valid_status ) ) { // Both scripts are yet to be run
        
        $message = '
                        <p>To ensure you experience a smooth migration to version 4.2.0, we need to run a DB Update. Please click on the Start button below for Step 1 of 2  to begin.</p>
                        <p><input type="submit" name="bkap_420_1" class="button-primary" value="Start" />
                            </p>';
        
            
    }else if ( isset( $plugin_version ) && '4.1.0' <= $plugin_version &&
        isset( $gcal_status_420 ) && !in_array( $gcal_status_420, $valid_status ) ) {
        $message = '
                        <p>Please click on the Start button below for Step 2 of 2 to begin.</p>
                        <p><input type="submit" name="bkap_420_2" class="button-primary" value="Start" />
                            </p>';
    }
    
    if ( isset( $db_status ) && 'success' === strtolower( $db_status ) && 
         isset( $db_status_410 ) && 'success' === strtolower( $db_status_410 ) &&
         isset( $db_status_420 ) && 'success' === strtolower( $db_status_420 ) &&
         isset( $gcal_status_420 ) && 'success' === strtolower( $gcal_status_420 ) ) {
        $message = 'The database update for Booking & Appointment plugin for WooCommerce was successful.';
    } else if ( ( isset( $db_status ) && 'fail' == strtolower( $db_status ) ) || 
        ( isset( $db_status_410 ) && 'fail' == strtolower( $db_status_410 ) ) || 
        ( isset( $db_status_420 ) && 'fail' == strtolower( $db_status_420 ) ) ||
        isset( $gcal_status_420 ) && 'fail' == strtolower( $gcal_status_420 ) ) {
        
        $manual_update_count = get_option( 'bkap_400_manual_update_count', 'woocommerce-booking' );
        $manual_update_count_410 = get_option( 'bkap_410_manual_update_count', 'woocommerce-booking' );
        $manual_update_count_420 = get_option( 'bkap_420_manual_update_count', 'woocommerce-booking' );
        
        if ( ( isset( $manual_update_count ) && '1' == $manual_update_count ) || 
            ( isset( $manual_update_count_410 ) && '1' == $manual_update_count_410 ) ||
            ( isset( $manual_update_count_420 ) && '1' == $manual_update_count_420 ) ) {
            
            $message = "<p>We have been unsuccessful in updating the database for Booking & Appointment plugin.</p>";
            
            $message .= "<p>Request you to kindly contact ";
            $message .= '<a href="http://feedback.tychesoftwares.com/">support</a>';
            $message .= " at Tyche Softwares.</p>";
                
        } else {
            
            $message = "";
            
            if( $db_status == 'fail' || $db_status_410 == 'fail' || $db_status_420 == 'fail' || $gcal_status_420 == 'fail' ){
                $message = "<p><h3>We need to update your database in order for Booking & Appointment Plugin to run smoothly.<h3></p><p><h3>Unfortunately, the automatic update has failed. Please click below to manually update the database.</h3></p>";
            }
            
            if( $db_status == 'fail' ){
                $message .= '<p>Database update based for changes in v4.0.0. Please <b><a href="javascript:void(0);" id="bkap_update_link" style="color:red;">click here</a></b>.</p>';
            }
            
            if( $db_status_410 == 'fail' ){
                $message .= '<p>Database update based on Fixed Block and Price by ranges changes in v4.1.0. Please <b><a href="javascript:void(0);" id="bkap_update_link_f_p" style="color:red;">click here</a></b>.</p>';
            }

            if( $db_status_420 == 'fail' || $gcal_status_420 == 'fail' ){
                $message .= '<p>Database update for changes in v4.2.0. Please <b><a href="javascript:void(0);" id="bkap_update_link_v420" style="color:red;">click here</a></b>.</p>';
            }
        }
        
    }
    
    _e( $message, 'woocommerce-booking' );
    ?>
    
    <div id="bkap_progress" style="display:none;"></div>
    <div id="bkap_result" style="display:none;"></div>
    <div id="bkap_progress_f_p" style="display:none;"></div>
    <div id="bkap_result_f_p" style="display:none;"></div>
    <br/>
    <br/>
    <br/>
    <br/>
    </form>
    <?php
}

/**
 * Will be run once on updating to version 4.0.0 or higher
 * 
 * For each product, it copies the serialized data to
 * individual post meta record for easier access
 * 
 * @param string $db_version - Version being updated to 
 * @since 4.0.0
 */

function bkap_400_update_settings( $db_version ) {
    
    global $wpdb;
    
    $all_products = bkap_common::get_woocommerce_product_list( false );
        
    $product_list = array();
    
    if ( isset( $all_products ) && count( $all_products ) > 0 ) {
        foreach( $all_products as $a_key => $a_value ) {
            $bookable = bkap_common::bkap_get_bookable_status( $a_value[ 1 ] );
            
            // if the product is bookable
            if ( $bookable ) {
                 $product_list[ $a_key ] = $a_value;
            }
        }
    }
    
    $db_version = str_replace( '.', '', $db_version );
    
    if ( isset( $product_list ) && count( $product_list ) > 0 ) {
        // total number of bookable products
        $total_bookable_count = count( $product_list );
        
        foreach( $all_products as $p_key => $p_value ) {
            
            // check if update status record exists
            $update_status = get_post_meta( $p_value[ 1 ], '_bkap_400_update_status', true );
            
            // if yes, skip the product
            if ( isset( $update_status ) && 'completed' == strtolower( $update_status ) ) {
                continue;
            } else { 
                $meta_key = "woocommerce_booking_settings_$db_version";
                
                $backup_data = get_post_meta( $p_value[ 1 ], $meta_key, true );
                
                if ( is_array( $backup_data ) && count( $backup_data ) > 0 ) {
                    // backup has been created.. so do nothing..  simply update       
                } else {
                    
                    $booking_settings = get_post_meta( $p_value[ 1 ], 'woocommerce_booking_settings', true );
                    // create a backup record
                    add_post_meta( $p_value[ 1 ], $meta_key, $booking_settings );
                }

                // copy the special prices into the new postmeta
                bkap_400_update_special( $p_value[ 1 ] );
                
                // convert the product holidays from string to an array
                bkap_400_update_holidays( $p_value[ 1 ] );
                
                // change the specific dates array format
                bkap_400_update_specific( $p_value[ 1 ] );

                // change the fixed range format
                bkap_400_update_ranges( $p_value[ 1] );

                // create recurring lockout
                bkap_400_update_recurring_lockout( $p_value[ 1 ] );

                // create recurring weekdays record and add maximum nights
                bkap_400_recurring_data( $p_value[ 1 ] );

                // update specific dates if needed
                bkap_400_update_enable_specific( $p_value[ 1 ] );
                
                bkap_400_update_enable_week_blocking( $p_value[ 1 ] );
                
                // create individualized booking meta data
                bkap_400_create_meta( $p_value[ 1 ] );
                
                add_post_meta( $p_value[ 1 ], '_bkap_400_update_status', 'completed' );
            }
            
        }
        
        if ( isset( $total_bookable_count ) && $total_bookable_count > 0 ) {
            // get the number of update status count

            $count_query = "SELECT Count( post_id) AS RecordCount FROM `" . $wpdb->prefix. "postmeta`
                            WHERE meta_key = %s";
            
            $get_count = $wpdb->get_results( $wpdb->prepare( $count_query, '_bkap_400_update_status' ) );
            
            $total_records = $get_count[ 0 ]->RecordCount;
            
            if ( $total_records == $total_bookable_count ) {
                $_status = 'success';
            } else {
                $_status = 'fail';
            }
            
            update_option( 'bkap_400_update_db_status', $_status );
        }
        
    }
    
}

/**
 * Will be run once on updating to version 4.1.0 or higher
 *
 * For each product, it copies the serialized data of Fixed Block Booking and Price By Range to 
 * individual post meta record for easier access
 * 
 * @param string $db_version - Version being updated to
 * @since 4.1.0
 */

function bkap_410_update_settings( $db_version ) {

    
    global $wpdb;

    $all_products = bkap_common::get_woocommerce_product_list_f_p( false ); // Getting all the product ids where price by range or fixed block booking is enabled.
     
    $product_list = $all_products;

    $db_version = str_replace( '.', '', $db_version );
    
    if ( isset( $product_list ) && count( $product_list ) > 0 ) {
        // total number of bookable products
        $total_bookable_count = count( $product_list );
    
    
        foreach( $all_products as $p_key => $p_value ) {
            
            // check if update status record exists
            $update_status = get_post_meta( $p_value[ 1 ], '_bkap_410_update_status', true );
            
            // if yes, skip the product
            if ( isset( $update_status ) && 'completed' == strtolower( $update_status ) ) {
                continue;
            } else {
                $meta_key = "woocommerce_booking_settings_f_p_$db_version";
            
                $backup_data = get_post_meta( $p_value[ 1 ], $meta_key, true );
            
                if ( is_array( $backup_data ) && count( $backup_data ) > 0 ) {
                    // backup has been created.. so do nothing..  simply update
                } else {
            
                    $booking_settings = get_post_meta( $p_value[ 1 ], 'woocommerce_booking_settings', true );
                    // create a backup record
                    add_post_meta( $p_value[ 1 ], $meta_key, $booking_settings );
                }
            
                // copy the fixed block booking into the new postmeta
                bkap_410_update_fixed_blocks( $p_value[ 1 ] );
                
                // copy the price by range into the new postmeta
                bkap_410_update_price_ranges( $p_value[ 1 ] );
                
                // Previously we were storing Booking Block Pricing and Price By Range as yes or no
                // Now we are storing as id of this options.
                bkap_410_update_block_pricing_option_values_in_new_way( $p_value[ 1 ] );
            
                // create individualized booking meta data for fixed blocks and price ranges
                bkap_410_create_meta( $p_value[ 1 ] );
            
                add_post_meta( $p_value[ 1 ], '_bkap_410_update_status', 'completed' );
            }
            
        }
        
        if ( isset( $total_bookable_count ) && $total_bookable_count > 0 ) {
            // get the number of update status count
        
            $count_query = "SELECT Count( post_id) AS RecordCount FROM `" . $wpdb->prefix. "postmeta`
                            WHERE meta_key = %s";
        
            $get_count = $wpdb->get_results( $wpdb->prepare( $count_query, '_bkap_410_update_status' ) );
        
            $total_records = $get_count[ 0 ]->RecordCount;
        
            if ( $total_records == $total_bookable_count ) {
                $_status = 'success';
            } else {
                $_status = 'fail';
            }
        
            update_option( 'bkap_410_update_db_status', $_status );
        }
    }
    
}

/**
 * For each product, it copies the serialized data of Fixed Block Booking and Price By Range to
 * individual post meta record for easier access
 * 
 * @param int $product_id
 * @since 4.1.0
 */

function bkap_410_create_meta( $product_id ) {
    
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );
     
    // Fixed Blocks
    $bkap_fixed_blocks_data = array();
    if ( isset( $booking_settings[ 'bkap_fixed_blocks_data' ] ) ) {
        $bkap_fixed_blocks_data = $booking_settings[ 'bkap_fixed_blocks_data' ];
    }
    
    // Fixed Blocks
    $bkap_price_range_data = array();
    if ( isset( $booking_settings[ 'bkap_price_range_data' ] ) ) {
        $bkap_price_range_data = $booking_settings[ 'bkap_price_range_data' ];
    }
    
    $meta_args = array(
        '_bkap_fixed_blocks_data'   => $bkap_fixed_blocks_data,
        '_bkap_price_range_data'    => $bkap_price_range_data
    );
    
    // run a foreach and save the data
    foreach ( $meta_args as $key => $value ) {
        update_post_meta( $product_id, $key, $value );
    }
}

/**
 * Fetch fixed blocks records from booking_fixed_blocks and update data
 * in the woocomemrce_booking_settings post meta.
 * 
 * @param int $product_id
 * @since 4.1.0
 */

function bkap_410_update_fixed_blocks( $product_id ) {
    
    global $wpdb;
    
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );
     
    $booking_fixed_block_enable = "";
    
    if( isset( $booking_settings['booking_fixed_block_enable'] ) && $booking_settings['booking_fixed_block_enable'] != "" ){
        $booking_fixed_block_enable = $booking_settings['booking_fixed_block_enable'];
    }
    
    // if the product is bookable
    if ( $booking_fixed_block_enable != "" ) {
    
        $fixed_query              =  "SELECT * FROM `".$wpdb->prefix."booking_fixed_blocks`
                                     WHERE post_id = %d";
            
        $fixed_results            =  $wpdb->get_results( $wpdb->prepare( $fixed_query, $product_id ) );
        
        $array_of_all_fixed_block_data = array();
        
        if( $fixed_results != "" && count($fixed_results) > 0 ){
            
            
            $i=0 ;
            
            foreach( $fixed_results as $fixed_results_key => $fixed_results_value ){
            
                $array_of_all_fixed_block_data[$i]['block_name']      = $fixed_results_value->block_name;
                $array_of_all_fixed_block_data[$i]['number_of_days']  = $fixed_results_value->number_of_days;
                $array_of_all_fixed_block_data[$i]['start_day']       = $fixed_results_value->start_day;
                $array_of_all_fixed_block_data[$i]['end_day']         = $fixed_results_value->end_day;
                $array_of_all_fixed_block_data[$i]['price']           = $fixed_results_value->price;
                $i++;
            }
        } 
        
        $booking_settings[ 'bkap_fixed_blocks_data' ] = $array_of_all_fixed_block_data;
        update_post_meta( $product_id , 'woocommerce_booking_settings', $booking_settings );
    }
}

/**
 * In version 4.0.0 we were saving Fixed Block and Price by range value as yes no.
 * Now in version 4.1.0 we are storing these options as "booking_fixed_block_enable" and "booking_block_price_enable" 
 *
 * @param int $product_id
 * @since 4.1.0
 */

function bkap_410_update_block_pricing_option_values_in_new_way( $product_id ){
    
    global $wpdb;
    
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );
     
    $booking_block_price_enable = "";
    $booking_fixed_block_enable = "";
    
    // fixed blocks
    if( isset( $booking_settings['booking_fixed_block_enable'] ) && $booking_settings['booking_fixed_block_enable'] != "" ){
        $booking_fixed_block_enable = $booking_settings['booking_fixed_block_enable'];
    }
    
    if( $booking_fixed_block_enable == "yes" ){
        $booking_fixed_block_enable = "booking_fixed_block_enable";
    }
    
    $booking_settings[ 'booking_fixed_block_enable' ] = $booking_fixed_block_enable;
    update_post_meta( $product_id , '_bkap_fixed_blocks', $booking_fixed_block_enable );
    
    // price by range
    if( isset( $booking_settings['booking_block_price_enable'] ) && $booking_settings['booking_block_price_enable'] != "" ){
        $booking_block_price_enable = $booking_settings['booking_block_price_enable'];
    }
    
    if( $booking_block_price_enable == "yes" ){
        $booking_block_price_enable = "booking_block_price_enable";
    }
    
    $booking_settings[ 'booking_block_price_enable' ] = $booking_block_price_enable;
    update_post_meta( $product_id , '_bkap_price_ranges', $booking_block_price_enable );
    
    update_post_meta( $product_id , 'woocommerce_booking_settings', $booking_settings );
    
}

/**
 * Fetch price ranges records from wp_booking_fixed_blocks and wp_booking_block_price_meta and update data
 * in the woocomemrce_booking_settings post meta.
 *
 * @param int $product_id
 * @since 4.1.0
 */
function bkap_410_update_price_ranges( $product_id ){
    
    global $wpdb;
    
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );
        
    $booking_block_price_enable = "";
    
    if( isset( $booking_settings['booking_block_price_enable'] ) && $booking_settings['booking_block_price_enable'] != "" ){
        $booking_block_price_enable = $booking_settings['booking_block_price_enable'];
    }
    
    // if the product is bookable
    if ( $booking_block_price_enable != "" ) {
        
        $join_sub_query = "";
        $c1 = "";
        $product        = wc_get_product( $product_id );
        $product_type   = $product->get_type();
        
        $demo_array     = array();
        $bkap_price_range_data = array();
        
        if( $product_type == 'variable' ) {
             
            $product_attributes      = get_post_meta( $product_id, '_product_attributes', true );
            $product_attributes_keys = array_keys( $product_attributes );
            $default_array           = array('min_number', 'max_number', 'per_day_price', 'fixed_price'); // default array
            $demo_array              = array_merge( $product_attributes_keys, $default_array ); // creating a demo array. This will help later to arrange the final price range data.
             
            if( is_array( $product_attributes ) && count( $product_attributes ) > 0 ){
                $join_sub_query = " JOIN `".$wpdb->prefix."booking_block_price_attribute_meta` AS c1 ON c0.id = c1.block_id";
                $c1 = ",c1.attribute_id,c1.meta_value";
            }
        }
            
        $price_query    = "SELECT c0.id,c0.minimum_number_of_days,c0.maximum_number_of_days,c0.price_per_day,c0.fixed_price".$c1." FROM `".$wpdb->prefix."booking_block_price_meta` AS c0
                          ".$join_sub_query."
                          WHERE c0.post_id = %d";
        
        $price_results  = $wpdb->get_results( $wpdb->prepare( $price_query, $product_id ) );
        
        $range_ids = array();
        $array_of_all_price_range_data = array(); // In this array we will store final records.
        $i = 0;
        
        if( $price_results != "" && count($price_results) > 0 ){
            
        
            foreach( $price_results as $price_results_key => $price_results_value ){
            
                $id               = $price_results_value->id;
                $min              = $price_results_value->minimum_number_of_days;
                $max              = $price_results_value->maximum_number_of_days;
                $per_day_price    = $price_results_value->price_per_day;
                $fixed_price      = $price_results_value->fixed_price;
            
                if( $c1 != "" ){
                    $att            = $price_results_value->attribute_id - 1; // we will get key which used to find the attribute name from $product_attributes_keys array
                    $attribute_name = $product_attributes_keys[$att]; // Got arribute name.
                    $att_val        =  $price_results_value->meta_value;
                }
            
                if( !in_array( $id, $range_ids ) ){
                     
                    $range_ids[ $i ] = $id;
            
                    if( $c1 != "" ){
                        $array_of_all_price_range_data[$i][$attribute_name]      = $att_val;
                    }
            
                    $array_of_all_price_range_data[$i]['min_number']      = $min;
                    $array_of_all_price_range_data[$i]['max_number']      = $max;
                    $array_of_all_price_range_data[$i]['per_day_price']   = $per_day_price;
                    $array_of_all_price_range_data[$i]['fixed_price']     = $fixed_price;
            
                     
                }else{
            
                    $j = array_search( $id, $range_ids );
            
                    if( $c1 != "" ){
                        $array_of_all_price_range_data[$j][$attribute_name]      = $att_val;
                    }
                }
                $i++;
            }
            
            
            if( $c1 != "" ){ // If poroduct is variable product then the array which we got is not in proper sequance as we want to store in post meta hence arranging the same here.
                $k = 0;
                foreach( $array_of_all_price_range_data as $array_of_all_price_range_data_key => $array_of_all_price_range_data_value ){
                    $bkap_price_range_data[$k] = array_replace( array_flip( $demo_array ), $array_of_all_price_range_data_value );
                    $k++;
                }
            }else{
                $bkap_price_range_data = $array_of_all_price_range_data;
            }
        }// end if.
        
        $booking_settings[ 'bkap_price_range_data' ] = $bkap_price_range_data;
        update_post_meta( $product_id , 'woocommerce_booking_settings', $booking_settings );
        
    }
}

/**
 * For each product, it copies the serialized data to
 * individual post meta record for easier access
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_create_meta( $product_id ) {
    
    // get the woocommerce booking settings record
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );
     
    $bookable = bkap_common::bkap_get_bookable_status( $product_id );
    
    // if the product is bookable
    if ( $bookable ) {
        
        // earlier, we did not save the booking type. We checked individual settings to determine the same
        // From now on, we will save the booking type, making it easier to determine the processing needed
        if ( isset( $booking_settings[ 'booking_enable_multiple_day' ] ) && 'on' == $booking_settings[ 'booking_enable_multiple_day' ] ) {
            $booking_type = 'multiple_days';
        } else if ( isset( $booking_settings[ 'booking_enable_time' ] ) && 'on' == $booking_settings[ 'booking_enable_time' ] ) {
            $booking_type = 'date_time';
        } else {
            $booking_type = 'only_day';
        }
         
        // set the default minimum number of days for multiple day booking to 0
        $multiple_min = 0;
        if ( isset( $booking_settings[ 'booking_minimum_number_days_multiple' ] ) && 'on' == $booking_settings[ 'booking_minimum_number_days_multiple' ] ) {
            $multiple_min = $booking_settings[ 'booking_minimum_number_days_multiple' ];
        }
        
        // set the default maximum number of days for multiple day booking to 365
        $multiple_max = 365;
        if ( isset( $booking_settings[ 'booking_maximum_number_days_multiple' ] ) ) {
            $multiple_max = $booking_settings[ 'booking_maximum_number_days_multiple' ];
        }
        
        // recurring lockout
        $recurring_lockout = array();
        if ( isset( $booking_settings[ 'booking_recurring_lockout' ] ) ) {
            $recurring_lockout = $booking_settings[ 'booking_recurring_lockout' ];
        }
        
        // price by range
        $price_ranges = '';
        if ( isset( $booking_settings[ 'booking_block_price_enable' ] ) ) {
            $price_ranges = $booking_settings[ 'booking_block_price_enable' ];
        }

        // fixed blocks
        $fixed_blocks = '';
        if ( isset( $booking_settings[ 'booking_fixed_block_enable' ] ) ) {
            $fixed_blocks = $booking_settings[ 'booking_fixed_block_enable' ];
        }
        
        // gcal automated mapping
        $automated_mapping = '';
        if ( isset( $booking_settings[ 'enable_automated_mapping' ] ) ) {
            $automated_mapping = $booking_settings[ 'enable_automated_mapping' ];
        }
        // gcal default variation
        $default_variation = 0;
        if ( isset( $booking_settings[ 'gcal_default_variation' ] ) ) {
            $default_variation = $booking_settings[ 'gcal_default_variation' ];
        }
        
        // create an array of the meta keys for individual data
        $meta_args = array(
            '_bkap_enable_booking' => $booking_settings[ 'booking_enable_date' ],
            '_bkap_booking_type' => $booking_type,
            '_bkap_enable_specific' => $booking_settings[ 'booking_specific_booking' ],
            '_bkap_enable_recurring' => $booking_settings[ 'booking_recurring_booking' ],
            '_bkap_specific_dates' => $booking_settings[ 'booking_specific_date' ],
            '_bkap_recurring_weekdays' => $booking_settings[ 'booking_recurring' ],
            '_bkap_recurring_lockout' => $recurring_lockout,
            '_bkap_enable_inline' => $booking_settings[ 'enable_inline_calendar' ],
            '_bkap_purchase_wo_date' => $booking_settings[ 'booking_purchase_without_date' ],
            '_bkap_requires_confirmation' => $booking_settings[ 'booking_confirmation' ],
            '_bkap_product_holidays' => $booking_settings[ 'booking_product_holiday' ],
            '_bkap_multiple_day_min' => $multiple_min,
            '_bkap_multiple_day_max' => $multiple_max,
            '_bkap_date_lockout' => $booking_settings[ 'booking_date_lockout' ],
            '_bkap_custom_ranges' => $booking_settings[ 'booking_date_range' ],
            '_bkap_abp' => $booking_settings[ 'booking_minimum_number_days' ],
            '_bkap_max_bookable_days' => $booking_settings[ 'booking_maximum_number_days' ],
            '_bkap_time_settings' => $booking_settings[ 'booking_time_settings' ],
            '_bkap_fixed_blocks' => $fixed_blocks,
            '_bkap_price_ranges' => $price_ranges,
            '_bkap_gcal_integration_mode' => $booking_settings[ 'product_sync_integration_mode' ],
            '_bkap_gcal_key_file_name' => $booking_settings[ 'product_sync_key_file_name' ],
            '_bkap_gcal_service_acc' => $booking_settings[ 'product_sync_service_acc_email_addr' ],
            '_bkap_gcal_calendar_id' => $booking_settings[ 'product_sync_calendar_id' ],
            '_bkap_enable_automated_mapping' => $automated_mapping,
            '_bkap_default_variation' => $default_variation,
            '_bkap_import_url' => $booking_settings[ 'ics_feed_url' ]
        );
        // run a foreach and save the data
        foreach ( $meta_args as $key => $value ) {
            update_post_meta( $product_id, $key, $value );
        }
    }
    
}

/**
 * We're moving the booking_special_price post meta record to 
 * _bkap_special_price from 4.0.0
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_update_special( $product_id ) {

    $special_prices = get_post_meta( $product_id, 'booking_special_price', true );

    update_post_meta( $product_id, '_bkap_special_price', $special_prices );

    delete_post_meta( $product_id, 'booking_special_price' );
}

/**
 * Up to v3.5.x holidays were saved as a string. From v4.0.0, they will 
 * be saved as an array where the date is the key and the number of years to 
 * recur is the value. 
 * 
 * This function modifies the old records to the new format for each 
 * bookable product.
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_update_holidays( $product_id ) {

    // get the woocommerce booking settings record
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );

    $holidays_list = array();

    $product_holidays = isset( $booking_settings[ 'booking_product_holiday' ] ) ? $booking_settings[ 'booking_product_holiday' ] : '';

    if ( ! is_array( $product_holidays ) && '' != $product_holidays ) {
        $explode_holidays = explode( ',', $product_holidays );

        if ( is_array( $explode_holidays ) && count( $explode_holidays ) > 0 ) {
            foreach( $explode_holidays as $h_date ) {
                if ( '' != $h_date ) {
                    $holidays_list[ $h_date ] = 0;
                }
            }
        }
    }

    $booking_settings[ 'booking_product_holiday' ] = $holidays_list;
    update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );
}

/**
 * Update function added for POS Addon compatibility.
 * 
 * @param integer $product_id - Product ID
 * @since 4.4.0
 */

function bkap_400_update_enable_week_blocking( $product_id ){
    
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );
    
    $wkpbk_block_single_week = $special_booking_start_weekday = $special_booking_end_weekday = '';

    if ( isset( $booking_settings [ 'wkpbk_block_single_week' ] ) ) {
        $wkpbk_block_single_week = $booking_settings [ 'wkpbk_block_single_week' ];
    }

    if ( isset( $booking_settings [ 'special_booking_start_weekday' ] ) ) {
        $special_booking_start_weekday = $booking_settings [ 'special_booking_start_weekday' ];
    }

    if ( isset( $booking_settings [ 'special_booking_end_weekday' ] ) ) {
        $special_booking_end_weekday = $booking_settings [ 'special_booking_end_weekday' ];
    }

    if( isset( $wkpbk_block_single_week ) && 'on' == $wkpbk_block_single_week ) {
        $booking_settings [ 'special_booking_start_weekday' ] = $special_booking_start_weekday;
        $booking_settings [ 'special_booking_end_weekday' ] = $special_booking_end_weekday;
    }

    update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );
}

/**
 * Upto v3.5.x specific dates were stored as array values. 
 * From v4.0.0 the date will be the key in the array and 
 * the lockout value will be stored as the array value.
 * 
 * This function will be run once on updating the plugin.
 * It will convert the old array to the new format.
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_update_specific( $product_id ) {

    global $wpdb;
    // get the woocommerce booking settings record
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );

    $specific_dates = array();

    $specific_list = isset( $booking_settings[ 'booking_specific_date' ] ) ? $booking_settings[ 'booking_specific_date' ] : '';

    if ( is_array( $specific_list ) && count( $specific_list ) > 0 ){

        foreach( $specific_list as $s_date ) {
            if ( '' != $s_date ) {
                $specific_date = date( 'Y-m-d', strtotime( $s_date ) );
                // find a record for the given date and product in the booking history table
                $query_specific = "SELECT total_booking FROM `" . $wpdb->prefix . "booking_history`
                                    WHERE post_id = %d
                                    AND start_date = %s
                                    AND weekday = ''";
                $get_specific = $wpdb->get_results( $wpdb->prepare( $query_specific, $product_id, $specific_date ) );

                if ( count( $get_specific ) > 0 ) {
                    $lockout = 0;
                    foreach( $get_specific as $s_lockout ) {
                        $lockout += $s_lockout->total_booking;
                    }
                    $specific_dates[ $s_date ] = $lockout;
                } else {
                    $specific_dates[ $s_date ] = 0;
                }
            }
        }
    }

    $booking_settings[ 'booking_specific_date' ] = $specific_dates;
    update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );

}

/**
 * Upto v3.5.x the plugin allowed only a single fixed range
 * From v4.0.0 the plugin will allow multiple ranges. Hence
 * this function modifies the way the data is stored.
 * lockout value will be stored as the array value.
 *
 * This function will be run once on updating the plugin.
 * It will convert the old data to the new format.
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_update_ranges( $product_id ) {

    // get the woocommerce booking settings record
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );

    // fixed range as custom ranges
    $fixed_range_array = array();

    if ( isset( $booking_settings[ 'booking_start_date_range' ] ) && '' != $booking_settings[ 'booking_start_date_range' ] && isset( $booking_settings[ 'booking_end_date_range' ] ) && '' != $booking_settings[ 'booking_end_date_range' ] ) {
        $fixed_range_array[] = array( 'start' => $booking_settings[ 'booking_start_date_range' ],
            'end' => $booking_settings[ 'booking_end_date_range' ],
            'years_to_recur' => $booking_settings[ 'booking_range_recurring_years' ]
        );

    }

    $booking_settings[ 'booking_date_range' ] = $fixed_range_array;
    unset( $booking_settings[ 'booking_start_date_range' ] );
    unset( $booking_settings[ 'booking_end_date_range' ] );
    unset( $booking_settings[ 'recurring_booking_range' ] );
    unset( $booking_settings[ 'booking_range_recurring_years' ] );
    unset( $booking_settings[ 'booking_date_range_type' ] );

    update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );
}

/**
 * Adds recurring weekday lockout records
 * for only day and date & time bookings.
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_update_recurring_lockout( $product_id ) {

    global $bkap_weekdays;
    global $wpdb;

    // get the woocommerce booking settings record
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );

    // nothing needs to be done for multiple day bookings
    if ( isset( $booking_settings[ 'booking_enable_multiple_day' ] ) && 'on' == $booking_settings[ 'booking_enable_multiple_day' ] ) {
        return;
    }

    $recurring_lockout = array();
    // get the weekdays array
    foreach( $bkap_weekdays as $w_key => $name ) {

        // find a record for the given day and product in the booking history table
        $query_recurring = "SELECT total_booking FROM `" . $wpdb->prefix . "booking_history`
                                    WHERE post_id = %d
                                    AND start_date = '0000-00-00'
                                    AND weekday = %s";
        $get_recurring = $wpdb->get_results( $wpdb->prepare( $query_recurring, $product_id, $w_key ) );

        if ( count( $get_recurring ) > 0 ) {
            $lockout = 0;
            foreach( $get_recurring as $r_lockout ) {
                $lockout += $r_lockout->total_booking;
            }
            $recurring_lockout[ $w_key ] = $lockout;
        } else {
            $recurring_lockout[ $w_key ] = '';
        }

    }

    $booking_settings[ 'booking_recurring_lockout' ] = $recurring_lockout;

    update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );

}

/**
 * Adds recurring weekday records & maximum nights for 
 * multiple day booking products.
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_recurring_data( $product_id ) {

    global $bkap_weekdays;
    global $wpdb;

    // get the woocommerce booking settings record
    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );

    // nothing needs to be done for multiple day bookings
    if ( isset( $booking_settings[ 'booking_enable_multiple_day' ] ) && 'on' == $booking_settings[ 'booking_enable_multiple_day' ] ) {
        $recurring_weekdays = array();

        // get the weekdays array
        foreach( $bkap_weekdays as $w_key => $name ) {
            $recurring_weekdays[ $w_key ] = 'on';
        }
        $booking_settings[ 'booking_recurring' ] = $recurring_weekdays;

        // add maximum nights as 365 by default
        $booking_settings[ 'booking_maximum_number_days_multiple' ] = 365;
    }

    update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );

}

/**
 * Enables specific date booking if it is off
 * This is needed if the product uses custom
 * ranges or holidays
 * 
 * @param int $product_id
 * @since 4.0.0
 */

function bkap_400_update_enable_specific( $product_id ) {

    $booking_settings = get_post_meta( $product_id, 'woocommerce_booking_settings', true );

    if ( isset( $booking_settings[ 'booking_specific_booking' ] ) && 'on' != $booking_settings[ 'booking_specific_booking' ] ) {

        $update_needed = false;
        // check if holidays have been set
        if ( is_array( $booking_settings[ 'booking_product_holiday' ] ) && count( $booking_settings[ 'booking_product_holiday' ] ) > 0 ) {
            $update_needed = true;
        }

        // check if custom ranges have been set
        if ( is_array( $booking_settings[ 'booking_date_range' ] ) && count( $booking_settings[ 'booking_date_range' ] ) > 0 ) {
            $update_needed = true;
        }

        // check if special prices have been set for a date
        $booking_special_prices = get_post_meta( $product_id, '_bkap_special_price', true );
        
        if ( is_array( $booking_special_prices ) && count( $booking_special_prices ) > 0 ) {
            foreach( $booking_special_prices as $s_key => $s_value ) {
                if ( isset( $s_value[ 'booking_special_date' ] ) && $s_value[ 'booking_special_date' ] != '' ) {
                    $update_needed = true;
                    break;
                }
            }
        }
        
        if ( $update_needed ) {
            $booking_settings[ 'booking_specific_booking' ] = 'on';
            update_post_meta( $product_id, 'woocommerce_booking_settings', $booking_settings );
        }
    }
}

/**
 * This function will fetch the individual booking settings
 * saved in post meta and push them in a single array
 * and return the same.
 * 
 * @return array $booking_settings
 * @since 4.0.0
 */

function bkap_get_post_meta( $product_id ) {

    $booking_settings = array();
    
    if ( isset( $product_id ) && $product_id > 0 ) {
        
        // create an array of the meta keys for individual data
        $meta_args = array(
            '_bkap_enable_booking',
            '_bkap_booking_type',
            '_bkap_enable_specific',
            '_bkap_enable_recurring',
            '_bkap_specific_dates',
            '_bkap_recurring_weekdays',
            '_bkap_recurring_lockout',
            '_bkap_enable_inline',
            '_bkap_purchase_wo_date',
            '_bkap_requires_confirmation',
            '_bkap_product_holidays',
            '_bkap_multiple_day_min',
            '_bkap_multiple_day_max',
            '_bkap_date_lockout',
            '_bkap_custom_ranges',
            '_bkap_abp',
            '_bkap_max_bookable_days',
            '_bkap_time_settings',
            '_bkap_fixed_blocks',
            '_bkap_price_ranges',
            '_bkap_gcal_integration_mode',
            '_bkap_gcal_key_file_name',
            '_bkap_gcal_service_acc',
            '_bkap_gcal_calendar_id',
            '_bkap_enable_automated_mapping',
            '_bkap_default_variation',
            '_bkap_import_url' 
        );
        
        // run a foreach and save the data
        foreach ( $meta_args as $key => $value ) {
            $temp = get_post_meta( $product_id, $value, true );
            
            switch( $value ) {
                case '_bkap_enable_booking':
                    $booking_settings[ 'booking_enable_date' ] = $temp;
                    break;
                case '_bkap_booking_type':
                    if ( 'multiple_days' == $temp ) {
                        $booking_settings[ 'booking_enable_multiple_day' ] = 'on';
                        $booking_settings[ 'booking_enable_time' ] = '';
                    } else if ( 'date_time' == $temp ) {
                        $booking_settings[ 'booking_enable_multiple_day' ] = '';
                        $booking_settings[ 'booking_enable_time' ] = 'on';
                    } else if ( 'only_day' == $temp ) {
                        $booking_settings[ 'booking_enable_multiple_day' ] = '';
                        $booking_settings[ 'booking_enable_time' ] = '';
                    }
                    break;
                case '_bkap_enable_specific': 
                    $booking_settings[ 'booking_specific_booking' ] = $temp;
                    break;
                case '_bkap_enable_recurring':
                    $booking_settings[ 'booking_recurring_booking' ] = $temp;
                    break;
                case '_bkap_specific_dates':
                    $booking_settings[ 'booking_specific_date' ] = $temp;
                    break;
                case '_bkap_recurring_weekdays':
                    $booking_settings[ 'booking_recurring' ] = $temp;
                    break;
                case '_bkap_recurring_lockout':
                    $booking_settings[ 'booking_recurring_lockout' ] = $temp;
                    break;
                case '_bkap_enable_inline':
                    $booking_settings[ 'enable_inline_calendar' ] = $temp;
                    break;
                case '_bkap_purchase_wo_date':
                    $booking_settings[ 'booking_purchase_without_date' ] = $temp;
                    break;
                case '_bkap_requires_confirmation':
                    $booking_settings[ 'booking_confirmation' ] = $temp;
                    break;
                case '_bkap_product_holidays':
                    $booking_settings[ 'booking_product_holiday' ] = $temp;
                    break;
                case '_bkap_multiple_day_min':
                    if ( $temp > 0 ) {
                        $booking_settings[ 'enable_minimum_day_booking_multiple' ] = 'on';
                        $booking_settings[ 'booking_minimum_number_days_multiple' ] = $temp;
                    } else {
                        $booking_settings[ 'enable_minimum_day_booking_multiple' ] = '';
                        $booking_settings[ 'booking_minimum_number_days_multiple' ] = 0;
                    }
                    break;
                case '_bkap_multiple_day_max':
                        $booking_settings[ 'booking_maximum_number_days_multiple' ] = $temp;
                    break;
                case '_bkap_date_lockout':
                    $booking_settings[ 'booking_date_lockout' ] = $temp;
                    break;
                case '_bkap_custom_ranges':
                    $booking_settings[ 'booking_date_range' ] = $temp;
                    break;
                case '_bkap_abp':
                    $booking_settings[ 'booking_minimum_number_days' ] = $temp;
                    break;
                case '_bkap_max_bookable_days':
                    $booking_settings[ 'booking_maximum_number_days' ] = $temp;
                    break;
                case '_bkap_time_settings':
                    $booking_settings[ 'booking_time_settings' ] = $temp;
                    break;
                case '_bkap_fixed_blocks':
             //       if ( isset( $temp ) && $temp != '' ) {
                        $booking_settings[ 'booking_fixed_block_enable' ] = $temp;
             //       }
                    break;
                case '_bkap_price_ranges':
              //      if ( isset( $temp ) && $temp != '' ) {
                        $booking_settings[ 'booking_block_price_enable' ] = $temp;
              //      }
                    break;
                case '_bkap_gcal_integration_mode':
                    $booking_settings[ 'product_sync_integration_mode' ] = $temp;
                    break;
                case '_bkap_gcal_key_file_name':
                    $booking_settings[ 'product_sync_key_file_name' ] = $temp;
                    break;
                case '_bkap_gcal_service_acc':
                    $booking_settings[ 'product_sync_service_acc_email_addr' ] = $temp;
                    break;
                case '_bkap_gcal_calendar_id':
                    $booking_settings[ 'product_sync_calendar_id' ] = $temp;
                    break;
                case '_bkap_enable_automated_mapping':
              //      if ( isset( $temp ) && $temp != '' ) {
                        $booking_settings[ 'enable_automated_mapping' ] = $temp;
              //      }
                    break;
                case '_bkap_default_variation':
                //    if ( isset( $temp ) && $temp > 0 ) {
                        $booking_settings[ 'gcal_default_variation' ] = $temp;
                //    }
                    break;
                case '_bkap_import_url':
                    $booking_settings[ 'ics_feed_url' ] = $temp;
                    break;
                default: 
                    break;
            }
        }
    }
    return $booking_settings;
}

/**
 * Creates bkap_booking posts for Order Items not having Booking details in post and post_meta
 * This is done for all the bookings placed before the plugin was updated to v4.0.0
 * 
 * @param string $limit_query Limit for SQL query. This function is executed in steps of 500
 * @return array $update_stats - Statistics of whether the update was successful for the given items
 * @since 4.2.0
 */

function bkap_420_update_settings( $limit_query ) {
    
    global $bkap_date_formats, $wpdb;
    $global_settings = json_decode( get_option( 'woocommerce_booking_global_settings' ) );
    $booking_obj = array();
    $update_stats = array();

    $order_migration_query = 
        "SELECT P1.ID, P2.booking_id, P3.order_item_id 
        FROM `" . $wpdb->prefix . "posts` AS P1 
        JOIN `" . $wpdb->prefix . "booking_order_history` AS P2 
        JOIN `" . $wpdb->prefix . "woocommerce_order_items` AS P3 
        WHERE P1.ID = P2.order_id AND P1.post_date > %s AND P1.ID = P3.order_id AND P3.order_item_type=%s $limit_query";

    $results_migration =   $wpdb->get_results ( $wpdb->prepare( $order_migration_query, '2017-01-01 00:00:00', 'line_item' ) );

    $item_count = $success_count = 0;
    $failed_items = array();

    foreach ( $results_migration as $results_value) {

        $order_item_id = (int)$results_value->order_item_id;
        $booking_exists = bkap_common::get_booking_id( $order_item_id );

        $product_item = new WC_Order_Item_Product($order_item_id);

        $product_id = $product_item->get_product_id( 'view' );
        $is_bookable = bkap_common::bkap_get_bookable_status( $product_id );
        
        if ( !$booking_exists && $is_bookable && isset( $product_item['_wapbk_booking_date'] ) ) {

            $item_count++;

            // default the variables
            $booking_obj['date'] = '';
            $booking_obj['hidden_date'] = '';
            $booking_obj['date_checkout'] = '';
            $booking_obj['hidden_date_checkout'] = '';
            $booking_obj['time_slot'] = '';
            $booking_obj['price'] = '';
            
            $booking_obj['date'] = date( $bkap_date_formats[$global_settings->booking_date_format], strtotime( $product_item['_wapbk_booking_date'] ) );
            $booking_obj['hidden_date'] = $product_item['_wapbk_booking_date'];
            
            if ( isset( $product_item['_wapbk_checkout_date'] ) ) {
                $booking_obj['date_checkout'] = date( $bkap_date_formats[$global_settings->booking_date_format], strtotime( $product_item['_wapbk_checkout_date'] ) );
                $booking_obj['hidden_date_checkout'] = $product_item['_wapbk_checkout_date'];
            }
            
            if ( isset( $product_item['_wapbk_time_slot'] ) ) {
                $booking_obj['time_slot'] = $product_item['_wapbk_time_slot'];
            }

            $booking_obj['price'] = $product_item->get_total( 'view' );

            $booking_post = bkap_checkout::bkap_create_booking_post( 
                $order_item_id, 
                $product_id, 
                $product_item->get_quantity( 'view' ), 
                $booking_obj, 
                $variation_id = '' );

            if ( $booking_post !== false ) {
                $success_count++;
            }else {
                array_push( $failed_items, $order_item_id );
            }

            $update_stats = array(
                'item_count' => $item_count,
                'post_count' => $success_count,
                'failed_count' => count( $failed_items ),
                'failed_items' => $failed_items
            );
        }
    }

    return $update_stats;
}

/**
 * Runs the DB Update process manually for v4.2.0
 *
 * @since 4.2.0
 */

function bkap_manual_db_update_v420() {
    
    $booking_plugin_version = '4.2.0';
    
    bkap_db_420_1();

    $return_status = get_option( 'bkap_420_update_db_status' );
    $gcal_status = get_option( 'bkap_420_update_gcal_status' );
    
    if ( 'success' == $return_status && 'success' === $gcal_status ) {
    

    } else {
        update_option( 'bkap_420_manual_update_count', '1' );
    }

    echo $return_status;

    die();
}

/**
 * This function will add a post meta record  '_bkap_gcal_event_uid' 
 * for all booking posts. This is being done to ensure orders created
 * from imported events are displayed in the new View Bookings page.
 *  
 * @since 4.2.0
 */

function bkap_420_gcal_meta() {

    $post_status = 'all';
    $bookings = bkap_common::bkap_get_bookings( $post_status );

    $gcal_meta = 0;
    
    if( is_array( $bookings ) && count( $bookings ) > 0 ) {
        foreach( $bookings as $booking ) {

            $booking_id = $booking->id;

            $item_id = get_post_meta( $booking_id, '_bkap_order_item_id', true );

            $gcal_event = wc_get_order_item_meta( $item_id, '_gcal_event_reference' );

            if ( isset( $gcal_event ) && count( $gcal_event ) > 1 ) {
                $uid = $gcal_event->uid;
                update_post_meta( $booking_id, '_bkap_gcal_event_uid', $uid );
                $gcal_meta++;
            }
        }
    }
    
    wp_reset_postdata();
    update_option( 'bkap_420_update_gcal_meta', $gcal_meta );
    
}

/**
 * Returns the number of batches (of 500 each) that are present
 * for imported events from Google Calendar
 *
 * @return integer $batch_size array
 * @since 4.2.0
 */

function bkap_420_gcal_batch_size(){

    global $wpdb;

    $events_query = "SELECT COUNT(*), option_name, option_value FROM `" . $wpdb->prefix . "options`
                        WHERE option_name LIKE %s";

    $events_list = $wpdb->get_var ( $wpdb->prepare( $events_query, 'bkap_imported_events_%' ) );

    $batch_size = ceil( $events_list / 500 );

    return $batch_size;
}

/**
 * This function will add a google calendar import post for all the 
 * existing unmapped events for the admin calendars. This is being 
 * done to ensure that the existing unmapped events are visible 
 * on the new Import page after upgrading the plugin.
 * 
 * @param string $limit_query Limit for SQL query. This function is executed in steps of 500
 * @return array $update_stats - Statistics of whether the update was successful for the given items
 * @since 4.2.0
 */

function bkap_420_add_gcal_posts( $limit_query ) {

    if ( strtolower( get_option( 'bkap_420_update_gcal_status' ) ) == 'success' )
        return;
    
    global $wpdb;

    // get all the option recordss
    $events_query = "SELECT option_name, option_value FROM `" . $wpdb->prefix . "options`
                        WHERE option_name LIKE %s $limit_query";

    $events_list = $wpdb->get_results( $wpdb->prepare( $events_query, 'bkap_imported_events_%' ) );

    $event_count = 0;
    $success_count = 0;
    $failed_items = array();
    
    $update_stats = create_posts( $events_list, $failed_items, $event_count, $success_count );
    
    $event_count = $update_stats[ 'item_count' ];
    $success_count = $update_stats[ 'post_count' ];
    $failed_items = $update_stats[ 'failed_items' ];
    
    // check if the tour operators addon is active and there are imported events for the operators
    /*if ( function_exists( 'is_bkap_tours_active' ) && is_bkap_tours_active() ) {
        $tours_query = "SELECT option_name, option_value FROM `" . $wpdb->prefix . "options`
                            WHERE option_name LIKE %s";
    
        $tours_list = $wpdb->get_results( $wpdb->prepare( $tours_query, 'tours_imported_events_%' ) );
    
        if ( is_array( $tours_query ) && count( $tours_list ) > 0 ) {
    
            $update_stats = create_posts( $tours_list, $failed_items, $event_count, $success_count );
    
            $event_count = $update_stats[ 'item_count' ];
            $success_count = $update_stats[ 'post_count' ];
            $failed_items = $update_stats[ 'failed_items' ];
    
        }
    }*/
    
    /*if ( $event_count === $success_count ) {
        $_status = 'success';
    } else {
        $_status = 'fail';
    }*/
    
    return $update_stats;
    /*if ( isset( $update_stats ) && isset( $_status ) ) {
        update_option( 'bkap_420_gcal_update_stats', $update_stats );
        //update_option( 'bkap_420_update_gcal_status', $_status );
    }*/
    
}

/**
 * This function will add a google calendar import post for all the
 * existing unmapped events for the tour operator calendars. This is being
 * done to ensure that the existing unmapped events are visible
 * on the new Import page after upgrading the plugin.
 *
 * @param string $limit_query Limit for SQL query. This function is executed in steps of 500
 * @return array $update_stats - Statistics of whether the update was successful for the given items
 * @since 4.2.0
 */

function bkap_420_add_gcal_tour_posts( $limit_query ) {

    global $wpdb;

    // check if the tour operators addon is active and there are imported events for the operators
    if ( function_exists( 'is_bkap_tours_active' ) && is_bkap_tours_active() ) {
        $tours_query = "SELECT option_name, option_value FROM `" . $wpdb->prefix . "options`
                            WHERE option_name LIKE %s $limit_query";
    
        $tours_list = $wpdb->get_results( $wpdb->prepare( $tours_query, 'tours_imported_events_%' ) );
    
        if ( is_array( $tours_list ) && count( $tours_list ) > 0 ) {

            $event_count = 0;
            $success_count = 0;
            $failed_items = array();
    
            $update_stats = create_posts( $tours_list, $failed_items, $event_count, $success_count );
    
            $event_count = $update_stats[ 'item_count' ];
            $success_count = $update_stats[ 'post_count' ];
            $failed_items = $update_stats[ 'failed_items' ];
            
            return $update_stats;
        }
    }
}

/**
 * Create GCAL posts for all the imported events
 *
 * @param resource $events_list - SQL Result of list of events present in wp_options
 * @param array $failed_items - Items for which creation of posts fails
 * @param integer $event_count - Total Event Count
 * @param integer $success_count - Count of events for which posts are created successfully
 * @return array $update_stats - Statistics of maping
 *
 *  @since 4.2.0
 */

function create_posts( $events_list, $failed_items, $event_count, $success_count ) {

    global $wpdb;

    $update_stats = array();

    if ( is_array( $events_list ) && count( $events_list ) > 0 ) {
        foreach( $events_list as $event_details ) {
            $event_value = json_decode( $event_details->option_value );

            $check_uid = "SELECT post_id FROM `" . $wpdb->prefix . "postmeta`
                            WHERE meta_key = %s
                            AND meta_value = %s";

            $uid_res = $wpdb->get_col( $wpdb->prepare( $check_uid, '_bkap_uid', $event_value->uid ) );
            // continue only if the event has not been mapped yet
            if ( isset( $uid_res ) && count( $uid_res ) > 0 )
                continue;

            $event_count++;

            $event_name = $event_details->option_name;

            $user_id = 1;
            $exp_option = explode( '_', $event_name );
            
            if ( $exp_option[0] === 'tours' ) {
                $user_id = trim( $exp_option[3] );
            }
            $gcal_event = bkap_calendar_sync::bkap_create_gcal_event_post( $event_value, 0 , 'bkap-unmapped', $event_name, $user_id );

            if ( $gcal_event !== false ) {
                $success_count++;
            }else {
                array_push( $failed_items, $event_details->option_name );
            }

            $update_stats = array(
                'item_count' => $event_count,
                'post_count' => $success_count,
                'failed_count' => count( $failed_items ),
                'failed_items' => $failed_items
            );

        }
    }

    return( $update_stats );
}

/**
 * Function to run the first step of DB Upgrade to version 4.2.0
 *
 * @param integer $count - Step count
 * @since 4.2.0
 */

function bkap_db_420_1( $count ) {
    
    $new_step = ( ( $count - 1 ) * 500 );

    $db_stats = array();

    // save the existing stats
    $db_stats = get_option( 'bkap_420_update_stats' );
    
    $sql = "LIMIT $new_step, 500";        
    $updated_stats = bkap_420_update_settings( $sql );

    $db_stats[] = $updated_stats;
    
    // get the update status
    $_status = get_option( 'bkap_420_update_db_status' );
    
    update_option( 'bkap_420_update_stats', $db_stats );
    
    return $_status;    
}

/**
 * Runs the second step of the DB update to version 4.2.0
 *
 * @param integer $count - Step count
 * @since 4.2.0
 */

function bkap_db_420_2( $count ) {
    
    $new_step = ( ( $count - 1 ) * 500 ) + 1;

    $db_stats = array();
    $tour_db_stats = array();

    // save the existing stats
    $db_stats = get_option( 'bkap_420_gcal_update_stats' );
    $tour_db_stats = get_option( 'bkap_420_gcal_update_tour_stats' );
    
    $sql = "LIMIT $new_step, 500";        
    $updated_stats = bkap_420_add_gcal_posts( $sql );

    if ( function_exists( 'is_bkap_tours_active' ) && is_bkap_tours_active() ) {
        $updated_tour_stats = bkap_420_add_gcal_tour_posts( $sql );
    }

    $db_stats[] = $updated_stats;
    $tour_db_stats[] = $updated_tour_stats;

    // get the update status
    $_status = get_option( 'bkap_420_update_gcal_status' );
    
    update_option( 'bkap_420_gcal_update_stats', $db_stats );
    update_option( 'bkap_420_gcal_update_tour_stats', $tour_db_stats );
    
    return $_status;    
}

/**
 * Returns the number of steps that need to be run for the DB Upgrade
 * for v4.2.0.
 * Migration of existing bookings to booking posts
 *
 * @return integer $loop - Number of loops that need to be run
 * @since 4.2.0
 */

function bkap_get_db_count() {
    
    global $wpdb;
    
    $order_migration_query =
    "SELECT COUNT(*), P1.ID, P2.booking_id, P3.order_item_id
        FROM `" . $wpdb->prefix . "posts` AS P1
        JOIN `" . $wpdb->prefix . "booking_order_history` AS P2
        JOIN `" . $wpdb->prefix . "woocommerce_order_items` AS P3
        WHERE P1.ID = P2.order_id AND P1.post_date > %s AND P1.ID = P3.order_id AND P3.order_item_type=%s";

    $migration_count =   ( $wpdb->get_var ( $wpdb->prepare( $order_migration_query, '2017-01-01 00:00:00', 'line_item' ) ) );
    
    $loops = ceil( $migration_count / 500 );
//    $loops = 4;
    return $loops;
    
}

/**
 * This function will sort the array by ascending order. Key of the array should be date in d-m-Y format
 * 
 * @param string $a1 Parameter for ORDER BY query
 * @param string $b1 Parameter for ORDER BY query
 * 
 * @return int return based on date difference
 * @since 4.4.0
 */
function bkap_orderby_date_key( $a1, $b1 ) {
    
    $format = 'd-m-Y';

    $a = strtotime( date_format(DateTime::createFromFormat( $format, $a1 ), 'Y-m-d H:i:s' ) );
    $b = strtotime( date_format(DateTime::createFromFormat( $format, $b1 ), 'Y-m-d H:i:s' ) );
    
    if ( $a == $b ) {
        return 0;
    } else if ( $a > $b ) {
        return 1;
    } else {
        return -1;
    }
}

/**
 * This function will return the variation ID of default variation for a 
 * given variable product.
 *
 * @param WC_Product $product - Product
 * @param array $attributes - Array of default attribute values
 * @return integer Default Variation ID
 * @since 4.8.0
 */

function bkap_find_matching_product_variation( $product, $attributes ) {

    foreach( $attributes as $key => $value ) {
        if( strpos( $key, 'attribute_' ) === 0 ) {
            continue;
        }

        unset( $attributes[ $key ] );
        $attributes[ sprintf( 'attribute_%s', $key ) ] = $value;
    }

    if ( class_exists('WC_Data_Store') ) {

        $data_store = WC_Data_Store::load( 'product' );
        return $data_store->find_matching_product_variation( $product, $attributes );

    } else {

        return $product->get_matching_variation( $attributes );
    }
}

/**
 * This function is used to sort the timeslot by from time ascending order
 *
 * @since 4.8.0
 */

function bkap_sort_by_from_time( $x, $y ) {
    
    return $x['from_slot_hrs'] - $y['from_slot_hrs'];
}
?>
API documentation generated by ApiGen