<?php
/*

This file houses all of the installation methods for the admin menus and posts

 */

function rentpress_installPlugin($reinstall = false)
{
    require_once RENTPRESS_PLUGIN_ADMIN_POSTS . 'register_rentpress_posts.php';
    rentpress_registerAllPostTypes();

    // add database tables
    require_once RENTPRESS_PLUGIN_DATA_MODEL . 'property_model.php';
    require_once RENTPRESS_PLUGIN_DATA_MODEL . 'floorplan_model.php';
    require_once RENTPRESS_PLUGIN_DATA_MODEL . 'unit_model.php';
    require_once RENTPRESS_PLUGIN_DATA_MODEL . 'refresh_model.php';
    require_once RENTPRESS_PLUGIN_DATA_ACCESS . 'data_layer.php';
    $manual_units = rentpress_getAllManualUnits();

    if ($reinstall) {
        rentpress_dropPropertyDBTable();
        rentpress_dropFloorplanDBTable();
        rentpress_dropRefreshDBTable();

        delete_option('rentpress_plugin_version');
        delete_option('rentpress_plugin_last_sync_attempt');
        delete_option('rentpress_cron_start_incremental_data_sync_index');

        // remove crons
        if (wp_next_scheduled('rentpress_cron_hook_start_incremental_data_sync')) {
            wp_clear_scheduled_hook('rentpress_cron_hook_start_incremental_data_sync');
        }
        if (wp_next_scheduled('rentpress_cron_hook_start_data_sync')) {
            wp_clear_scheduled_hook('rentpress_cron_hook_start_data_sync');
        }
        if (wp_next_scheduled('rentpress_cron_hook_sync_data')) {
            wp_clear_scheduled_hook('rentpress_cron_hook_sync_data');
        }
        if (wp_next_scheduled('rentpress_cron_hook_sync_manual_data')) {
            wp_clear_scheduled_hook('rentpress_cron_hook_sync_manual_data');
        }
        if (wp_next_scheduled('rentpress_cron_hook_start_manual_data_sync')) {
            wp_clear_scheduled_hook('rentpress_cron_hook_start_manual_data_sync');
        }
    }

    rentpress_dropUnitDBTable();
    rentpress_makeUnitDBTable();
    rentpress_makePropertyDBTable();
    rentpress_makeFloorplanDBTable();
    rentpress_makeRefreshDBTable();

    foreach ($manual_units as $manual_unit) {
        $manual_unit_array = (array) $manual_unit;
        rentpress_saveUnitData($manual_unit_array);
    }

    if (!get_option('rentpress_flush_rewrite_rules_flag')) {
        add_option('rentpress_flush_rewrite_rules_flag', true);
    }
    if (!get_option('rentpress_plugin_version')) {
        add_option('rentpress_plugin_version', RENTPRESS_PLUGIN_VERSION);
    }
    if (!get_option('rentpress_plugin_last_sync_attempt')) {
        add_option('rentpress_plugin_last_sync_attempt', null);
    }
}