<?php
$show_init_form = false;	/* To display or not the initialization form */

/* Try to see if the call is from administration panel */
if(isset($admin_catdom_module_id) && $admin_catdom_module_id>0 && isset($_GET['action']) && $_GET['action'] == "custom_module") {
    $show_init_form = true;
    // Initialize defaults

    $def_ads = "no";
    $ws_ad_unit_id = "";
    $tv_ext_channels = [];
    $tv_ext_title = '';

    $current_catdom_module_id = $admin_catdom_module_id;
}

if($show_init_form) {
    // Try to get any previously saved customization
    if(isset($module_params) && is_array($module_params)) {
        foreach ($module_params as $key=>$value) {
            ${$key} = $value;
        }
    }

    $num_ext = count($tv_ext_channels);

    $channels = [];
    $q = "SELECT * FROM tv_channels WHERE is_active='1' ORDER BY name ASC;";
    $r = @mysql_query($q);
    if($r && mysql_num_rows($r) > 0) {
        $num = mysql_num_rows($r);
        $cnt = 1;
        while($row = mysql_fetch_assoc($r)) {
            $channel_id = intval($row['id']);
            $channel_name = trim(stripslashes($row['name']));

            if(isset($tv_ext_channels[$channel_id])) {
                $channels[$channel_id] = [
                    'name' => $channel_name,
                    'pos' => $tv_ext_channels[$channel_id]['pos'],
                    'selected' => $tv_ext_channels[$channel_id]['selected']
                ];
            }
            else {
                $pos = $num_ext + 1;
                $num_ext += 1;
                $channels[$channel_id] = [
                    'name' => $channel_name,
                    'pos' => $pos,
                    'selected' => 0
                ];
            }


            $cnt++;
        }
    }
    if(count($channels) > 0) {
        //echo '<pre>', var_export($channels, true), '</pre>';
        function compare_by_pos($a, $b) {
            if ($a['pos'] == $b['pos']) {
                return 0;
            }
            return ($a['pos'] < $b['pos']) ? -1 : 1;
        }
        uasort($channels, "compare_by_pos");
    }

    // Google ads related
    // Pull in the NuSOAP code
    require_once(dirname(__FILE__) . "/../wsbin/lib/nusoap.php");
    include_once(dirname(__FILE__) . "/../common/gads_content/functions.php");

    //$webservices_url = "http://localhost/webservices/cyws/srvdispatcher.php?wsdl";
    $webservices_url = "https://www.apps24.com/srvdispatcher.php?wsdl";

    $out_path_cache = dirname(__FILE__) . "/../..";
    $all_cache_folder = "$out_path_cache/all_cache/" . $app_conf["addonname"];
    $all_cache_folder = str_ireplace("//", "/", $all_cache_folder);
    $all_cache_normal_gads_content = "$all_cache_folder/gads_content";

    if(isset($module_params['ws_ad_unit_id']) && $module_params['ws_ad_unit_id'] >0) {
        $ad_unit_id = $module_params['ws_ad_unit_id'];
    }
    $ws_request_available_ad_units = array(
        'server_name' 		=> 'gads_content',
        'function_name'		=> 'getAdSenseContentUnits',
        'function_params'	=> ''
    );

    /* Check if cache folders are in place ******************************************************/
    if(!file_exists("$all_cache_folder") || !is_dir("$all_cache_folder")) {
        if( mkdir("$all_cache_folder", 0755) ) {

            if( mkdir("$all_cache_normal_gads_content", 0755) ) {
                //echo "<br/>$all_cache_normal_gads_content created";
            }
            else {
                //echo "<br/>Cannot create dir [$all_cache_normal_gads_content]";
            }
        }
        else {
            //echo "<br/>Cannot create dir [$all_cache_folder]";
        }
    }
    else {
        if(!file_exists("$all_cache_normal_gads_content") || !is_dir("$all_cache_normal_gads_content")) {
            if( mkdir("$all_cache_normal_gads_content", 0755) ) {
                //chmod("$general_path/all_cache/weather", 777);
                //echo "<br/>$all_cache_normal_gads_content created";
            }
            else {
                //echo "<br/>Cannot create dir [$all_cache_normal_gads_content]";
            }
        }
    }
    /* END Check for cache folders  *************************************************************/

    $have_it_on_cache = false;
    $md5 = md5(serialize($ws_request_available_ad_units));
    $cache_file = $all_cache_normal_gads_content . "/" . $md5;
    if(file_exists($cache_file)) {
        //echo "<br/>[$cache_file] exists";
        $cache_time = filemtime($cache_file);
        $current_time = time();
        if($current_time - $cache_time < 120) {
            $have_it_on_cache = true;
            //echo "<br/>$cache_file time is earlier than 15 min";
        }
        else {
            unlink($cache_file);
            //echo "<br/>$cache_file time is older than 15 min";
        }
    }
    if($have_it_on_cache) {
        $cache_get = file_get_contents($cache_file);

        if($cache_get != "") {
            $cache_get = unserialize($cache_get);
            $current_ad_units = $cache_get;
        }
    }
    else {
        //echo "<br/> --- here";
        $current_ad_units = getAdSenseContentUnits($webservices_url, $ws_request_available_ad_units);
        //echo "<br/>DO NOT Have it on cache";
        $cache_put = serialize($current_ad_units);
        if( true == ($fc = fopen($cache_file, "w") ) ) {
            fwrite($fc, $cache_put, strlen($cache_put));
            fclose($fc);
        }
    }


    ?>
    <form method="POST" action="custom_module_update.php" name="tv_frm" id="tv_frm">
        <div class="inline_container">
            <table cellpadding="0" cellspacing="0" border="0" width="100%">
                <tr>
                    <th colspan="2" align="left">
                        TV Module Customization
                    </th>
                </tr>
                <tr>
                    <td class="itdh">Display Title</td>
                    <td class="itd_lb">
                        <input type="text" name="tv_ext_title" value="<?=$tv_ext_title?>" style="width:100%;">
                    </td>
                </tr>
                <tr>
                    <td colspan="2" class="itd_lb">
                        <table cellpadding="0" cellspacing="0" width="100%">
                            <thead>
                            <tr>
                                <th>Pos</th>
                                <th>Channel Name</th>
                                <th>Show?</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                            if(count($channels) > 0) {
                                $cnt = 1;
                                foreach($channels as $id=>$ch) {
                                    ?>
                                    <tr>
                                        <td>
                                            <select name="tv_ext_channels[<?=$id;?>][pos]">
                                                <?php
                                                for($i=1; $i<=$num; $i++) {
                                                    $selected = "";
                                                    if(intval($ch['pos']) == $i) $selected ='selected="selected"';
                                                    echo '<option value="' . $i . '" '.$selected.'>' . $i . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td><?=$ch['name'];?></td>
                                        <td>
                                            <select name="tv_ext_channels[<?=$id;?>][selected]">
                                                <?php
                                                $opts = [
                                                    '1' => 'Yes',
                                                    '0' => 'No'
                                                ];
                                                foreach($opts as $ov=>$ol) {
                                                    $selected = "";
                                                    if(intval($ch['selected']) == intval($ov)) $selected ='selected="selected"';
                                                    echo '<option value="' . $ov . '" '.$selected.'>' . $ol . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </td>
                                    </tr>
                                    <?php
                                    $cnt++;
                                }
                            }
                            ?>
                            </tbody>
                        </table>
                    </td>
                </tr>

                <tr>
                    <td class="itdh">Display Ads?</td>
                    <td class="itd_lb">
                        <select name="def_ads">
                            <option value="yes" <?php echo $def_ads == "yes" ? 'selected="selected"': '';?>>Yes</option>
                            <option value="no" <?php echo $def_ads == "no" ? 'selected="selected"': '';?>>No</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td class="itdh">Select Ad Type</td>
                    <td class="itd_lb">
                        <div style="width: 100%; height: 400px; overflow-y:auto;">
                            <table cellpadding="0" cellspacing="0" border="0" width="100%">
                                <?php
                                if(isset($current_ad_units) && count($current_ad_units) > 0) {
                                    $types = array("text_image" => "Text & Image", "text" => "Text Only", "image" => "Image Only");
                                    $current_type = "";
                                    $current_type_name = "";
                                    foreach ($current_ad_units as $i => $row) {
                                        $ws_ad_unit_id = $row['ws_ad_unit_id'];
                                        $ws_ad_unit_name = stripslashes($row['ws_ad_unit_name']);
                                        $ws_ad_unit_type = $row['ws_ad_unit_type'];
                                        $ws_ad_unit_format = $row['ws_ad_unit_format'];
                                        $ws_ad_unit_palette = $row['ws_ad_unit_palette_name'];
                                        $ws_ad_unit_code = $row['ws_ad_unit_code'];
                                        $ws_ad_unit_active = ($row['ws_ad_unit_active'] == 1) ? "Active" : "Inactive";

                                        $checked = "";
                                        if (isset($ad_unit_id) && $ad_unit_id == $ws_ad_unit_id) {
                                            $checked = " checked";
                                        }

                                        if ($ws_ad_unit_type != $current_type) {
                                            $current_type = $ws_ad_unit_type;
                                            $current_type_name = $types[$ws_ad_unit_type];

                                            ?>
                                            <tr>
                                                <td class="itdh" colspan="4"><strong><?php echo $current_type_name; ?></strong></td>
                                            </tr>
                                            <?php
                                        }
                                        ?>
                                        <tr>
                                            <td class="itd"><input type="radio" name="ws_ad_unit_id"
                                                                   value="<?php echo $ws_ad_unit_id; ?>" <?php echo $checked; ?>
                                                                   class="radio_locations"/></td>
                                            <td class="itd_lb"><?php echo $ws_ad_unit_name; ?></td>
                                            <td class="itd_lb"><?php echo $ws_ad_unit_format; ?></td>
                                            <td class="itd_lb"><?php echo $ws_ad_unit_palette; ?></td>
                                        </tr>
                                        <?php
                                    }
                                }
                                ?>
                            </table>
                        </div>
                    </td>
                </tr>


                <tr>
                    <td colspan="2" align="right" class="footer">
                        <input type="reset" value="Reset" name="submit" class="submit_button"/>
                        <input type="submit" value="Save" name="submit" class="submit_button"/>
                        <input type="hidden" value="<?php echo $current_catdom_module_id; ?>" name="admin_catdom_module_id" id="admin_catdom_module_id"/>
                    </td>
                </tr>
            </table>
        </div>

    </form>
    <?php

    $module_forms = array(
        "form_name" => "tv_frm",
        "form_action" => "",
        "form_method" => "POST"
    );
}
else {
    // We are in the front-end
    // Initialize defaults
    $def_ads = "no";
    $ws_ad_unit_id = "";
    $tv_ext_channels = [];
    $tv_ext_title = '';

    // Try to get any customization done
    if(isset($module_params) && is_array($module_params)) {
        foreach ($module_params as $key=>$value) {
            ${$key} = $value;
        }
    }
}
?>