<?php
$page_title = (isset($_GET['item_id'])) ? 'Edit Channel' : 'Add Channel';
include("includes/header.php");
require_once("thumbnail_images.class.php");

$qry = "SELECT * FROM tbl_category order by cid DESC";
$cat_result = mysqli_query($mysqli, $qry);



if (isset($_POST['submit']) and isset($_GET['add'])  && PURCHASE == '') {
    // if (
    //     (!isset($_POST['category_id']) || count($_POST['category_id']) <= 0) ||
    //     empty(validate_input($_POST['iteam_name'])) ||
    //     empty(validate_input($_POST['type'])) ||        
    //     (!isset($_FILES['channel_poster']['size']) || $_FILES['channel_poster']['size'] == 0)        
    // ) {
    //     $_SESSION['msg'] = "15";
    //     $_SESSION['class'] = 'error';
    //     header("Location:add_album.php?add=yes");
    //     exit;
    // }


    $channel_poster = rand(0, 99999) . "_" . $_FILES['channel_poster']['name'];
    $pic1 = $_FILES['channel_poster']['tmp_name'];

    $tpath1 = 'images/' . $channel_poster;
    copy($pic1, $tpath1);

    $thumbpath = 'images/thumbs/' . $channel_poster;
    
    $obj_img = new thumbnail_images();
    $obj_img->PathImgOld = $tpath1;
    $obj_img->PathImgNew = $thumbpath;
    $obj_img->NewWidth = 270;
    $obj_img->NewHeight = 390;
    if (!$obj_img->create_thumbnail_images()) {
        echo $_SESSION['msg'] = "Thumbnail not created... please upload image again";
        exit;
    }
    
    

        $data = array(
            // 'cat_id'  =>  implode(',', $_POST['category_id']),            
            'cat_id'  =>  $_POST['category_id'],            
            'iteam_name'  =>  validate_input($_POST['iteam_name']),
            'image'  =>  validate_input($channel_poster),           
            'iteam_subscription_type'  =>  $_POST['type'],            
        );    
        echo "Helloooo";
    $qry = Insert('tbl_iteams', $data);

    $_SESSION['msg'] = "10";
    header("Location:manage_album.php");
    exit;
}
$count = 0;
if (isset($_GET['item_id'])) {
    $qry = "SELECT * FROM tbl_iteams where itemid='" . $_GET['item_id'] . "'";
    $result = mysqli_query($mysqli, $qry);
    $row = mysqli_fetch_assoc($result);
    $count = $result->num_rows;
}

if (isset($_POST['submit']) &&  $_POST['item_id'] && PURCHASE == '') {
    // if (
    //     (!isset($_POST['category_id']) || count($_POST['category_id']) <= 0) ||
    //     empty(validate_input($_POST['iteam_name'])) ||
    //     empty(validate_input($_POST['type']))
    // ) {
    //     $_SESSION['msg'] = "15";
    //     $_SESSION['class'] = 'error';
    //     header("Location:add_album.php?item_id=" . $_GET['item_id']);
    //     exit;
    // }

    if ($_FILES['channel_poster']['error'] != 4) {

        unlink('images/' . $row['channel_poster']);
        unlink('images/thumbs/' . $row['channel_poster']);

        $channel_poster = rand(0, 99999) . "_" . $_FILES['channel_poster']['name'];
        $pic1 = $_FILES['channel_poster']['tmp_name'];


        $tpath1 = 'images/' . $channel_poster;
        copy($pic1, $tpath1);

        $thumbpath = 'images/thumbs/' . $channel_poster;

        $obj_img = new thumbnail_images();
        $obj_img->PathImgOld = $tpath1;
        $obj_img->PathImgNew = $thumbpath;
        $obj_img->NewWidth = 270;
        $obj_img->NewHeight = 390;
        if (!$obj_img->create_thumbnail_images()) {
            echo $_SESSION['msg'] = "Thumbnail not created... please upload image again";
            exit;
        }
    } else {
        $channel_poster = $row['image'];
    }

  echo "hellooo";


        $data = array(
            'cat_id'  =>  $_POST['category_id'],            
            'iteam_name'  =>  validate_input($_POST['iteam_name']),
            'image'  =>  validate_input($channel_poster),           
            'iteam_subscription_type'  =>  $_POST['type'],            
        );
        echo "hellooo2";
        print_r($data);
    $channel_edit = Update('tbl_iteams', $data, "WHERE itemid = '" . $_POST['item_id'] . "'");

    $_SESSION['msg'] = "11";
    header("Location:manage_album.php");
    exit;
}
?>
<main id="main" class="main">
    <section class="section">
        <div class="row  g-3">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body g-3"><br>
                        <div class="pagetitle mb-5">
                            <h1><?php _e($page_title); ?></h1>

                        </div><!-- End Page Title -->
                        <!-- Floating Labels Form -->
                        <form class="row g-3" action="" name="addeditcategory" method="post" enctype="multipart/form-data">
                            <br><br>
                            <input type="hidden" name="item_id" value="<?php if ($count > 0) {
                                                                                _e($row['itemid']);
                                                                            } ?>" />
                            <div class="col-12">
                                <label for="inputNanme4" class="form-label">Category </label>
                                <select name="category_id" multiple class="form-control label ui selection fluid dropdown">
                                    <option value="" disabled>--Select Category --</option>
                                    <?php
                                    while ($categorys = mysqli_fetch_array($cat_result)) { ?>
                                        <option value="<?php _e($categorys['cid']); ?>" <?php if ($count > 0) {
                                                                                            if (in_array($categorys['cid'], explode(",", $row['cat_id']))) { ?>selected<?php }
                                                                                                                                                                } ?>><?php _e($categorys['category_name']); ?></option>
                                    <?php }
                                    ?>
                                </select>
                            </div>
                            <div class="col-12">
                                <label for="inputNanme4" class="form-label">Iteam Name :-</label>
                                <input type="text" class="form-control" name="iteam_name" id="iteam_name" value="<?php if ($count > 0) {
                                                                                                                            _e($row['iteam_name']);
                                                                                                                        }  ?>" class="form-control">
                            </div>
                            <div class="col-12">
                                <label for="inputNanme4" class="form-label">Type </label>
                                <select name="type" class="form-control label ui selection fluid dropdown">
                                    <option value="free" <?php if ($count > 0 && $row['iteam_subscription_type'] == 'free') { ?>selected<?php } ?>>FREE</option>
                                    <option value="paid" <?php if ($count > 0 && $row['iteam_subscription_type'] == 'paid') { ?>selected<?php } ?>>PAID</option>                                    
                                </select>
                            </div>
                      
                            <div class="col-12">
                                <label for="inputNanme4" class="form-label">Image :- </label>
                                <input type="file" name="channel_poster" class="form-control" value="fileupload" accept=".png,.PNG,.jpg, .JPG ,.jpeg,.JPEG" onchange="fileValidation()" id="fileupload">
                                <?php if ($count > 0) { ?>
                                    <div class="fileupload_img" id="uploadPreview"><img type="image" src="images/<?php _e($row['image']); ?>" alt="image" style="width: 150px;height:200px;margin-top: 10px;" /></div>
                                <?php } else { ?>
                                    <div class="fileupload_img" id="uploadPreview"><img type="image" src="assets/img/add-image.png" alt="image" style="width: 150px;height:200px;margin-top: 10px;" /></div>
                                <?php } ?>
                            </div>                                                                                                                                           

                            <div class="text-center">
                                <button type="submit" name="submit" class="btn button btn-primary <?php _e(PURCHASE); ?>">Save</button>
                                <button type="reset" class="btn btn-secondary">Reset</button>
                            </div>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </section>
</main><!-- End #main -->
<script type="text/javascript">
    function fileValidation() {
        var fileInput = document.getElementById('fileupload');
        var filePath = fileInput.value;
        var allowedExtensions = /(\.png|.PNG|.jpg|.JPG|.jpeg|.JPEG)$/i;
        if (!allowedExtensions.exec(filePath)) {
            alert('Please upload file having extension .png, .PNG, .JPG , .jpg,.jpeg,.JPEG only.');
            fileInput.value = '';
            return false;
        } else {
            //image preview
            if (fileInput.files && fileInput.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('uploadPreview').innerHTML = '<img src="' + e.target.result + '" style="width:150px;height:200px;margin-top: 10px;"/>';
                };
                reader.readAsDataURL(fileInput.files[0]);
            }
        }
    }

    function fileValidationCover() {
        var fileInput = document.getElementById('fileupload_img');
        var filePath = fileInput.value;
        var allowedExtensions = /(\.png|.PNG|.jpg|.JPG|.jpeg|.JPEG)$/i;
        if (!allowedExtensions.exec(filePath)) {
            alert('Please upload file having extension .png, .PNG, .JPG , .jpg,.jpeg,.JPEG only.');
            fileInput.value = '';
            return false;
        } else {
            //image preview
            if (fileInput.files && fileInput.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('uploadPreview_img').innerHTML = '<img src="' + e.target.result + '" style="width:150px;height:200px;margin-top: 10px;"/>';
                };
                reader.readAsDataURL(fileInput.files[0]);
            }
        }
    }

    function fileValidationSeries() {
        var fileInput = document.getElementById('fileupload_series');
        var files = fileInput.files;
        var uploadPreview = document.getElementById('uploadPreview_series');
        uploadPreview.innerHTML = '';

        var row = document.createElement('div');
        row.classList.add('row');

        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var allowedExtensions = /(\.png|\.PNG|\.jpg|\.JPG|\.jpeg|\.JPEG)$/i;

            if (!allowedExtensions.exec(file.name)) {
                alert('Please upload files having extensions .png, .PNG, .JPG, .jpg, .jpeg, .JPEG only.');
                fileInput.value = '';
                return false;
            } else {
                if (file) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var preview = document.createElement('img');
                        preview.src = e.target.result;
                        preview.style.width = '150px';
                        preview.style.height = '200px';
                        preview.style.marginTop = '10px';

                        var column = document.createElement('div');
                        column.classList.add('col-md-6');
                        column.appendChild(preview);
                        row.appendChild(column);
                    };
                    reader.readAsDataURL(file);
                }
            }
        }
        uploadPreview.appendChild(row);
    }
</script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        var userAgentSelect = document.getElementById('user_agent');
        var userAgentTypeDiv = document.getElementById('user_agent_type');
        var userAgentNameDiv = document.getElementById('user_agent_id');
        var userAgentTypeSelect = document.querySelector('select[name="user_agent_type"]');

        function handleFormState() {
            if (userAgentSelect.value === 'true') {
                userAgentTypeDiv.style.display = 'block';
                if (userAgentTypeSelect.value === 'custom') {
                    userAgentNameDiv.style.display = 'block';
                } else {
                    userAgentNameDiv.style.display = 'none';
                }
            } else {
                userAgentTypeDiv.style.display = 'none';
                userAgentNameDiv.style.display = 'none';
            }
        }
        userAgentSelect.addEventListener('change', function() {
            handleFormState();
        });
        userAgentTypeSelect.addEventListener('change', function() {
            if (this.value === 'custom') {
                userAgentNameDiv.style.display = 'block';
            } else {
                userAgentNameDiv.style.display = 'none';
            }
        });
        handleFormState();
    });
</script>
<?php include("includes/footer.php"); ?>