<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Associate']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    if(isset($_GET["user"])){
        $userId = $_GET["user"];
        $user_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$userId' ");
        if($user_row = mysqli_fetch_assoc($user_sql)){
            $userName = $user_row["uname"];
            $usertype = $user_row["utype"];
        }
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_run = mysqli_query($con, "SELECT * FROM data  WHERE data_sl_no = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                    ?>
                <div class="card">
                    <div class="card-header">
                        <h4 class="m-0">Edit Document : <?php echo $edit_row["data_title"];?></h4>
                    </div>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="data_up_for" class="form-label">Document For
                                        <?php echo $user_row["utype"]; ?></label>
                                    <select name="data_up_for" class="form-control">
                                        <option value="<?php echo $userId; ?>"><?php echo $userName; ?></option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="data_title" class="form-label">Document Title</label>
                                    <input type="text" class="form-control" name="data_title"
                                        value="<?php echo $edit_row["data_title"]?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="logo" class="form-label">Upload Document <?php if (!empty($edit_row["data_img"])) {
                                            $filePath = $edit_row["data_img"];
                                            $fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

                                            // Check the file type and display appropriately
                                            if (in_array($fileExtension, ['jpg', 'jpeg', 'png', 'gif'])) {
                                                // Image file
                                                echo "
                                                <a href='$filePath' title='Click to open' target='_blank'>
                                                    (<b>View Uploaded - <img src='$filePath' height='20' data-toggle='modal' data-target='#show-img' class='showModal'></b>)
                                                </a>";
                                            } elseif ($fileExtension === 'pdf') {
                                                // PDF file
                                                echo "
                                                <a href='$filePath' title='Click to open' target='_blank'>
                                                    (<b>View Uploaded - Document</b>)
                                                </a>";
                                            } elseif (in_array($fileExtension, ['doc', 'docx'])) {
                                                // Word document
                                                echo "
                                                <a href='$filePath' title='Click to open' target='_blank'>
                                                    (<b>View Uploaded - Document</b>)
                                                </a>";
                                            } else {
                                                // Unsupported file type
                                                echo "<p>(Unsupported file type)</p>";
                                            }
                                        } ?></label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        placeholder="Upload logo" accept=".jpg, .jpeg, .png, .gif, .pdf">
                                </div>
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-success btn-user my-2" name="edit_blog">
                                        <i class="fa fa-edit"></i> Update
                                    </button>
                                    <a href="uplodDocuments.php?user=<?php echo $userId;?>&show_list"
                                        class="btn btn-warning btn-user m-2 text-white"> <i
                                            class="fa fa-arrow-left"></i>
                                        Back </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["view_id"])){
                    $view_sql = "SELECT * FROM data WHERE data_sl_no='$_GET[view_id]'";
                    $view_data = mysqli_query($con,$view_sql);
                    if($view_rows = mysqli_fetch_array($view_data)){
                    ?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="m-0">Document Title : <span
                                class="underline"><?php echo $view_rows['data_title']; ?></span></h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <?php if (!empty($view_rows['data_img'])) { ?>
                            <h5 class="underline">Uplod Document</h5>
                            <?php if (!empty($view_rows['data_img'])) {
                                $filePath = $view_rows["data_img"];
                                $fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    
                                // Check the file type and display appropriately
                                if (in_array($fileExtension, ['jpg', 'jpeg', 'png', 'gif'])) {
                                    // Display image with modal
                                    echo "
                                    <a href='$filePath' title='Click to open' target='_blank'>
                                        <b>Already Uploaded - <img src='$filePath' height='50' data-toggle='modal' data-target='#show-img' class='showModal'></b>
                                    </a>";
                                } elseif ($fileExtension === 'pdf') {
                                    // Link to open PDF
                                    echo "
                                    <a href='$filePath' title='Click to open' target='_blank'>
                                        <b>Already Uploaded - PDF Document</b> (Click To View)
                                    </a>";
                                } elseif (in_array($fileExtension, ['doc', 'docx'])) {
                                    // Link to open DOC/DOCX file
                                    echo "
                                    <a href='$filePath' title='Click to open' target='_blank'>
                                        <b>Already Uploaded - Word Document</b> (Click To View)
                                    </a>";
                                } else {
                                    // Handle unsupported file types
                                    echo "<p>Unsupported file type.</p>";
                                }
                            } }  ?>
                        </div>
                        <hr>
                        <div class="mb-2">
                        </div>
                        <p><strong>Documents Upload by : </strong>
                            <?php 
                            $upBy_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$view_rows[data_up_by]' ");
                            if($upBy_row = mysqli_fetch_assoc($upBy_sql)){
                                echo $upBy_row["uname"];
                            }
                            ?>
                        </p>
                        <p><strong>Documents Upload Date : </strong><?php echo $view_rows['data_up_date']; ?></p>
                        <?php if(!empty($view_rows['data_edit_date'])){?>
                        <p><strong>Documents Edit Date : </strong><?php echo $view_rows['data_edit_date']; ?></p>
                        <?php }?>
                        <hr>
                        <a href="uplodDocuments.php?user=<?php echo $userId;?>&show_list"
                            class="btn btn-warning btn-user my-2 text-white"> <i class="fa fa-arrow-left"></i>
                            Back </a>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["add_new"])){?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="card-title mb-0">Add Document</h4>
                    </div>
                    <div class="card-body">
                    </div>
                </div>
                <?php }?>
                <?php if(isset($_GET["show_list"])){?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h4 class="text-gray-800">Document List for <?php echo $userName;?></h4>
                            </div>
                            <div class="col-md-4 d-flex justify-content-between">
                                <div>
                                    <button id="toggleButton" class="btn btn-primary btn-sm" onclick="toggleDiv()">Add
                                        Document
                                    </button>
                                </div>
                                <div class="d-flex">
                                    <div style="margin-left:18px;">
                                        <div class="form-group w-100">
                                            <input type="text" list="First" class="form-control form-control-sm"
                                                id="FirstFilterValue" placeholder="Search By Document Title">
                                            <datalist id="First">
                                                <?php 
                                                    $sql = "SELECT data_title FROM data WHERE data_catagory = 'Documents' AND data_recycle = '1' AND data_up_for = '$userId' ORDER BY data_sl_no DESC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['data_title']; ?>">
                                                    <?php echo $row['data_title']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <input type="hidden" class="form-control" value="" id="SecondFilterValue">
                                    </div>
                                    <div class="#">
                                        <button type="button" id="filter" class="btn btn-primary btn-sm"><i
                                                class="fa fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-12 mb-2">
                                <div id="toggleDiv"
                                    style="display: none; padding: 10px; border: 1px solid #ddd; margin-top: 10px;">
                                    <h5>Add Document:</h5>
                                    <form action="" method="POST" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label for="data_up_for" class="form-label">Document For
                                                    <?php echo $user_row["utype"]; ?></label>
                                                <select name="data_up_for" class="form-control">
                                                    <option value="<?php echo $userId; ?>"><?php echo $userName; ?>
                                                    </option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label for="data_title" class="form-label">Document Title</label>
                                                <input type="text" class="form-control" name="data_title"
                                                    placeholder="Enter Document Title">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label for="logo" class="form-label">Upload Document</label>
                                                <input type="file" name="logo" id="logo" class="form-control"
                                                    placeholder="Upload logo" accept=".jpg, .jpeg, .png, .gif, .pdf">
                                            </div>
                                            <div class="mb-3">
                                                <button class="btn btn-success text-white me-md-2" name="addsubmit"
                                                    type="submit">
                                                    <i class="fa fa-paper-plane"></i> Submit
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding-left: 0;">
                                    <?php
                                    for ($count = 0; $count < 4; $count++) {
                                        echo '<li>
                                        <div class="ph-item">
                                        <div cl ass="ph-test">
                                        <div class="ph-row">
                                        <div class="ph-col-12 big"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        </div>
                                        </div>
                                        </div>
                                        </li>';
                                        }
                                    ?>
                                </ul>
                            </div>

                            <!-- loader -->
                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="col-12" id="filter-table" style="display: none;">
                                <ul class="timeline" id="filter-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>

    <script>
    function toggleDiv() {
        const div = document.getElementById('toggleDiv');
        const button = document.getElementById('toggleButton');

        if (div.style.display === 'none' || div.style.display === '') {
            div.style.display = 'block';
            button.textContent = 'Hide';
        } else {
            div.style.display = 'none';
            button.textContent = 'Add Document';
        }
    }
    //dropdown TWO filter Start//
    $(document).ready(function() {
        var load_filter_flag = '';
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var data_up_for = '<?php echo $userId;?>';

        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            load_filter_flag = 0;
            if (FirstFilterValue != '' || SecondFilterValue != '') {
                //alert(name);
                $.ajax({
                    url: 'uplodDocuments-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        data_up_for: data_up_for,
                        start: load_filter_flag
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);
                        load_filter_flag += 10;
                    },
                    complete: function(data) {
                        /* Hide loader container */
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Plz Select an Option');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        function loadMoreFilter(start) {
            console.log('Filter' + start);
            if (load_filter_flag > 0) {
                //alert(name);
                $.ajax({
                    url: 'uplodDocuments-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        data_up_for: data_up_for,
                        start: start
                    },
                    success: function(result) {
                        $('#filter-table-data').append(result);
                        load_filter_flag += 10;
                    }
                });
            }
        }
        // Scroll Loading of Full Data //
        var load_flag = 0;
        loadMore(load_flag);

        function loadMore(start) {
            //console.log('total'+start);
            $.ajax({
                url: 'uplodDocuments-Ajax.php',
                type: 'POST',
                data: {
                    data_up_for: data_up_for,
                    start: start
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10;
                },
                complete: function(data) {
                    /* Hide loader container */
                    $("#loader").hide();
                }
            });
        }

        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() >= $(document).height() - $('#inner-body').height()) {
                //console.log('call');
                if (load_filter_flag > 0) {
                    loadMoreFilter(load_filter_flag);
                } else {
                    loadMore(load_flag);
                }
            }
        });
    });
    </script>

</body>

</html>


<!-- Add to database-->
<?php
if (isset($_POST['addsubmit'])) {
    $title = mysqli_real_escape_string($con, strip_tags($_POST['data_title']));
    $data_up_for = mysqli_real_escape_string($con, strip_tags($_POST['data_up_for']));

    $prefix = "uplodDocuments"; // Your prefix
    $random_number = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
    $timestamp = date("YmdHis"); 

    $ref_id = $prefix . $random_number . $timestamp;
    
    $up_date = date("j F, Y, g:i a");
    $recycle = "1";
    $up_by = $_SESSION['uid'];
    $catagory = 'Documents';

    // New File Upload
    $logopath = '';
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/uplodDocuments/";
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));

        // Generate a unique file name
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;

        $uploadOk = 1;

        // Get file MIME type
        $fileType = mime_content_type($_FILES["logo"]["tmp_name"]);

        if ($fileType !== false) {
            // Allow images, PDFs, and document files
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];

            if (in_array($fileType, $allowedTypes)) {
                $uploadOk = 1;
            } else {
                $uploadOk = 0;
                echo "<script>alert('File type not allowed. Please upload an image (JPEG, PNG, GIF), PDF, or DOC/DOCX file.');</script>";
            }
        } else {
            $uploadOk = 0;
            echo "<script>alert('Unable to determine file type. Please try again.');</script>";
        }

        // Check file size (5MB maximum)
        if ($_FILES["logo"]["size"] > 5000000) {
            $uploadOk = 0;
            echo "<script>alert('Sorry, your file is too large. Maximum size is 5MB.');</script>";
        }

        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 1) {
            // Try to upload the file
            if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
                $logopath = $target_file;
            } else {
                echo "<script>alert('Sorry, there was an error uploading your file.');</script>";
            }
        }
    }

    // Define $short_des, $long_des, and $subCategory as needed or comment them if not used
    $short_des = ''; // or fetch from POST
    $long_des = '';  // or fetch from POST
    $subCategory = ''; // or fetch from POST

    $courseCatagory_sql = "INSERT INTO data (data_ref_id, data_catagory, data_title, data_img, data_short_des, data_long_des, data_up_by, data_up_date, data_recycle, data_subCategory, data_up_for) VALUES ('$ref_id', '$catagory', '$title', '$logopath', '$short_des', '$long_des', '$up_by', '$up_date', '$recycle', '$subCategory', '$data_up_for')";

    if (mysqli_query($con, $courseCatagory_sql)) {
        ?>
<script>
alert("Details Sent Successfully");
window.location = "uplodDocuments.php?user=<?php echo $_GET['user']; ?>&show_list";
</script>
<?php
    } else {
        ?>
<script>
alert("Something's Wrong");
window.location = "uplodDocuments.php?user=<?php echo $_GET['user']; ?>&add_new";
</script>
<?php
    }
}
?>



<!-- Edit database  Blog-->
<?php
if (isset($_POST['edit_blog'])) {
    $title = mysqli_real_escape_string($con, strip_tags($_POST['data_title']));
    $data_up_for = mysqli_real_escape_string($con, strip_tags($_POST['data_up_for']));

    // Get existing data for image handling
    $existingImage = $edit_row["data_img"];

    // File Upload Logic
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/uplodDocuments/";
        $fileType = mime_content_type($_FILES["logo"]["tmp_name"]);
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));

        // Generate a unique file name
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;

        // Validate the file
        $uploadOk = 1;

        // Allowable MIME types
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];

        if ($fileType !== false && in_array($fileType, $allowedTypes)) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
            echo "<script>alert('File type not allowed. Please upload an image (JPEG, PNG, GIF), PDF, or DOC/DOCX file.');</script>";
        }

        // Check file size (5MB maximum)
        if ($_FILES["logo"]["size"] > 5000000) {
            $uploadOk = 0;
            echo "<script>alert('File size too large. Maximum allowed size is 5MB.');</script>";
        }

        // Attempt to upload if validations pass
        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
                // Unlink (delete) old file if it exists
                if (!empty($existingImage) && file_exists($existingImage)) {
                    unlink($existingImage);
                }
                $logopath = $target_file;
            } else {
                echo "<script>alert('Error uploading the new file.');</script>";
            }
        } else {
            echo "<script>alert('File validation failed.');</script>";
        }
    } else {
        // If no new file, keep the old file path
        $logopath = $existingImage;
    }

    // Update the database
    $update_sql = "UPDATE data SET data_title = '$title', data_img = '$logopath', data_up_for = '$data_up_for' WHERE data_ref_id = '{$edit_row['data_ref_id']}'";

    if (mysqli_query($con, $update_sql)) {
        ?>
<script>
alert("Details Updated Successfully");
window.location = "uplodDocuments.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
    } else {
        ?>
<script>
alert("Something went wrong while updating.");
window.location = "uplodDocuments.php?user=<?php echo $userId;?>&edit";
</script>
<?php
    }
}
?>



<!-- Recycle database  uplodDocuments-->
<?php
  if ( isset($_GET["rec_id"]) ) {
    $find_sql = "SELECT * FROM data WHERE data_sl_no = '$_GET[rec_id]'";
    $find_run = mysqli_query($con, $find_sql);
    if ($f_rows = mysqli_fetch_assoc($find_run)) {
        $old_rec = $f_rows["data_recycle"];
    
        if ($old_rec == 1) {
            $new_rec = 0;
        } elseif ($old_rec == 0) {
            $new_rec = 1;
        }
    
        $update_sql = "UPDATE data SET data_recycle = '$new_rec' WHERE data_sl_no = '$_GET[rec_id]'";
        $update_run = mysqli_query($con, $update_sql);

        if ( $update_run ) {
            ?>
<script>
alert("Sent to Recycle Successfully");
window.location = "uplodDocuments.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
        } else {
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'uplodDocuments.php?user=<?php echo $userId;?>&show_list';
}, 1200);
</script>
<?php
        }
        
    }

}
?>


<!-- delete database  Blog-->
<?php
if (isset($_GET["del_id"])) {
    $id = mysqli_real_escape_string($con, $_GET["del_id"]);
    
    $find_sql = "SELECT * FROM data WHERE data_sl_no = '$id'";
    $find_run = mysqli_query($con, $find_sql);

    if ($f_rows = mysqli_fetch_assoc($find_run)) {
        $old_img = $f_rows['data_img'];

        if (!empty($old_img)) {
            $previous_image_path = '../upload/uplodDocuments/' . $old_img;

            if (file_exists($previous_image_path)) {
                if (unlink($previous_image_path)) {
                    // Image deleted successfully
                } else {
                    // Failed to delete image
                    echo "Error deleting image: " . mysqli_error($con);
                }
            }
        }
    }

    $delete_sql = "DELETE FROM data WHERE data_sl_no = '$id'";
    
    if (mysqli_query($con, $delete_sql)) {
        ?>
<script>
alert("Deleted Successfully");
window.location = "uplodDocuments.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
    } else {
        ?>
<script>
alert("Failed to delete");
window.location = "uplodDocuments.php?user=<?php echo $userId;?>&show_list";
</script>
<?php
    }
}
?>