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

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['uref_code']) && !isset($_SESSION['uname']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }
    // echo $_SESSION["otp"];
    // echo $_SESSION["uref_code"];
    if(isset($_GET["product_id"])){}
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->
    <?php if(isset($_GET["product_id"])){
        $product_id = $_GET["product_id"];

        $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pid = '$product_id' ");
        if($product_row = mysqli_fetch_assoc($product_sql)){
            $client_id = $product_row["pClient"];
            $product = $product_row["product"];

            $service_sql = mysqli_query($con, "SELECT * FROM data WHERE data_sl_no = '$product' ");
            if($service_row = mysqli_fetch_assoc($service_sql)){
                $serviceName = $service_row["data_title"];
            }
        }
        $client_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$client_id' ");
        if($client_row = mysqli_fetch_assoc($client_sql)){
            $client_name = $client_row["uname"];
            $clientAdmin = $client_row["admin_ref"];
        ?>

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_id = $_GET["edit_id"];
                    $edit_run = mysqli_query($con, "SELECT * FROM documents WHERE did = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Client Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row justify-content-center">
                                <div class="col-md-7">
                                    <label for="title">Edit Document Type</label>
                                    <input type="text" class="form-control" name="dTitle"
                                        value="<?php echo $edit_row['dTitle']; ?>">
                                </div>
                                <div class="col-md-7">
                                    <p><strong>Document Preview :</p>
                                    <div>
                                        <?php 
                                            $document = $edit_row["document"];
                                            $file_ext = strtolower(pathinfo($document, PATHINFO_EXTENSION));
                                            $document_url = "../upload/documents/" . $document;

                                            // Display the file based on its type
                                            if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                                                echo '<img src="' . $document_url . '" alt="Document Image" style="max-width: 100%; height: auto;">';
                                            } elseif ($file_ext == 'pdf') {
                                                echo '<iframe src="' . $document_url . '" width="100%" height="600px"></iframe>';
                                            } elseif (in_array($file_ext, ['doc', 'docx'])) {
                                                echo '<a href="' . $document_url . '" target="_blank">Download Word Document</a>';
                                            } elseif (in_array($file_ext, ['xls', 'xlsx'])) {
                                                echo '<a href="' . $document_url . '" target="_blank">Download Excel Document</a>';
                                            } else {
                                                echo '<a href="' . $document_url . '" target="_blank">Download File</a>';
                                            }
                                        ?>
                                    </div>
                                    <label for="document">Enter Document</label>
                                    <input type="file" class="form-control" name="document">
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user m-2" name="edit_doc">
                                    <i class="fa fa-edit"></i> UPDATE DETAILS
                                </button>
                                <a href="view-documents.php?product_id=<?php echo $product_id;?>"
                                    class="btn btn-warning btn-user m-2">
                                    <i class="fa fa-ban"></i> Cancel
                                </a>
                            </div>
                        </form>

                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["view_id"])){
                    $edit_id = $_GET["view_id"];
                    $edit_run = mysqli_query($con, "SELECT * FROM documents WHERE did = '$_GET[view_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">View Documents Details</h5>
                    <div class="card-body">
                        <p><strong>Documents Title :</strong> <?php echo $edit_row["dTitle"];?></p>
                        <p><strong>Document Preview :</p>
                        <div>
                            <?php 
                            $document = $edit_row["document"];
                            $file_ext = strtolower(pathinfo($document, PATHINFO_EXTENSION)); // Get file extension
                            
                            $document_url = "../upload/documents/" . $document; // Assuming your files are stored in the "documents" directory
                            
                            // Display the file based on its type
                            if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                                // Display image
                                echo '<img src="' . $document_url . '" alt="Document Image" style="max-width: 100%; height: auto;">';
                            } elseif ($file_ext == 'pdf') {
                                // Display PDF in an iframe or object tag
                                echo '<iframe src="' . $document_url . '" width="100%" height="600px"></iframe>';
                            } elseif (in_array($file_ext, ['doc', 'docx'])) {
                                // Provide a link to download Word document
                                echo '<a href="' . $document_url . '" target="_blank">Download Word Document</a>';
                            } elseif (in_array($file_ext, ['xls', 'xlsx'])) {
                                // Provide a link to download Excel document
                                echo '<a href="' . $document_url . '" target="_blank">Download Excel Document</a>';
                            } else {
                                // Provide a download link for other file types
                                echo '<a href="' . $document_url . '" target="_blank">Download File</a>';
                            }
                            ?>
                        </div>
                        <a href="view-documents.php?product_id=<?php echo $product_id;?>"
                            class="btn btn-warning btn-user m-2"> <i class="fa fa-ban"></i>
                            Cancel </a>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["add_id"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Documents For
                        <span style="color:orange;"><?php echo $client_name;?>'s</span> <?php echo $serviceName;?>
                    </h5>
                    <div class="card-body">
                        <form action="" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="title">Enter Document Type</label>
                                    <input type="text" class="form-control" name="dTitle"
                                        placeholder="Enter Docyment Title">
                                </div>
                                <div class="col-md-6">
                                    <label for="document">Enter Document</label>
                                    <input type="file" class="form-control" name="document">
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user m-2" name="submit">
                                    <i class="fa fa-plus"></i> Add Files
                                </button>
                                <a href="view-documents.php?product_id=<?php echo $product_id;?>"
                                    class="btn btn-warning btn-user m-2">
                                    <i class="fa fa-ban"></i> Cancel
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php
                } else{?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-9 col-12 mt-2 mb-2">
                                <div class="row justify-content-between align-items-center">
                                    <div class="col-md-10 col-8 mb-2">
                                        <h4 class="text-gray-800 m-0">Documents List of <span
                                                style="color:orange;"><?php echo $serviceName;?></span></h4>
                                    </div>
                                    <div class="col-md-2 col-4 text-center">
                                        <a href="view-documents.php?product_id=<?php echo $product_id;?>&add_id"
                                            class="btn btn-primary btn-sm position-relative m-0"><i
                                                class="fa fa-plus position-absolute"
                                                style="left:0;top:0;font-size:17px;"></i>&nbsp;
                                            Document</a>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 col-12 mt-2 mb-2 d-flex justify-content-center">
                                <div class="form-group w-100">
                                    <input type="text" list="First" class="form-control form-control-sm"
                                        id="FirstFilterValue" placeholder="Search By Name">
                                    <datalist id="First">
                                        <?php 
                                            $uids = []; // Initialize an empty array to store the uids

                                            $users_sql = mysqli_query($con, "SELECT uid FROM users WHERE admin_ref = '" . mysqli_real_escape_string($con,   $_SESSION['uref_code']) . "'");
                                    
                                            while ($users_row = mysqli_fetch_assoc($users_sql)) {
                                                $uids[] = $users_row['uid']; // Add each uid to the array
                                            }

                                            $sql = "SELECT DISTINCT dClient, dTitle FROM documents ORDER BY did ASC";
                                            $res = mysqli_query($con,$sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                                if(in_array($row["dClient"], $uids)){
                                        ?>
                                        <option value="<?php echo $row['dTitle']; ?>">
                                            <?php echo $row['dTitle']; ?></option>
                                        <?php } } ?>
                                    </datalist>
                                </div>
                                <div class="#">
                                    <button type="button" id="filter" class="btn btn-primary btn-sm"> Search </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12">
                                <div>
                                    <h5 class="m-0">Required Documents :</h5>
                                    <div id="ck-img-preview">
                                        <?php echo $service_row['data_seo_title'];?>
                                    </div>
                                </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-left: 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-left: 0;">
                                    </>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <?php } }?>

    <!-- JavaScript Libraries -->

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

    <script>
    $(document).ready(function() {
        var load_filter_flag = '';
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var ThirdFilterValue = '';
        var ProductValue = <?php echo $product_id;?>; // Ensure ProductValue is initialized
        var load_flag = 0;

        // When the filter button is clicked
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            ThirdFilterValue = $('#ThirdFilterValue').val();
            ProductValue = $('#ProductValue').val();
            load_filter_flag = 0;

            if (FirstFilterValue != '' || ProductValue != '' || ThirdFilterValue != '') {
                $.ajax({
                    url: 'view-documents-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        productValue: ProductValue, // Fix capitalization
                        ThirdFilterValue: ThirdFilterValue,
                        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) {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Please select an option');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        // Function to load more filtered data
        function loadMoreFilter(start) {
            if (load_filter_flag > 0) {
                $.ajax({
                    url: 'view-documents-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        ProductValue: ProductValue, // Include product ID
                        ThirdFilterValue: ThirdFilterValue,
                        start: start
                    },
                    success: function(result) {
                        $('#filter-table-data').append(result);
                        load_filter_flag += 10;
                    }
                });
            }
        }

        // Scroll Loading of Full Data
        loadMore(load_flag);

        // Modified loadMore to include ProductValue
        function loadMore(start) {
            $.ajax({
                url: 'view-documents-Ajax.php',
                type: 'post',
                data: {
                    start: start,
                    productValue: ProductValue // Include product ID in the request
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10;
                },
                complete: function(data) {
                    $("#loader").hide();
                }
            });
        }

        // Scroll event to load more data
        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() >= $(document).height() - $('#inner-body').height()) {
                if (load_filter_flag > 0) {
                    loadMoreFilter(load_filter_flag);
                } else {
                    loadMore(load_flag);
                }
            }
        });
    });
    </script>

</body>

</html>

<?php
if (isset($_POST['submit'])) {
    // Fetch form inputs
    $dTitle = mysqli_real_escape_string($con, $_POST['dTitle']);

    $fran = $_SESSION["uid"];

    $subFran = '';
    if($clientAdmin == $_SESSION["uref_code"]){
        $subFran = '0';
    }else{
        $admin_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '$clientAdmin' ");
        if($admin_row = musqli_fetch_assoc($admin_sql)){
            $subFran = $admin_row["uid"];
        }
    }

    // Handle file upload
    if (isset($_FILES['document']['name']) && $_FILES['document']['name'] != '') {
        $file_name = $_FILES['document']['name'];
        $file_tmp = $_FILES['document']['tmp_name'];
        $file_size = $_FILES['document']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        // Allowed file extensions
        $allowed_ext = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];

        if (in_array($file_ext, $allowed_ext)) {
            // Create unique file name
            $new_file_name = uniqid() . '.' . $file_ext;

            // File upload path
            $upload_dir = "../upload/documents/";
            $upload_file = $upload_dir . $new_file_name;

            // Compress the image if it's jpg/jpeg/png (optional for other file types)
            if (in_array($file_ext, ['jpg', 'jpeg', 'png'])) {
                compressImage($file_tmp, $upload_file, 75); // Compress image and upload
            } else {
                move_uploaded_file($file_tmp, $upload_file); // Directly upload other file types
            }

            // Insert into database
            $sql = "INSERT INTO documents (dTitle, document, dProduct, dClient, dUpby, dCreateDate, dRecycle, dFranchiee, dSubFranchiee) VALUES ('$dTitle', '$new_file_name', '$product_id', '$client_id', '$_SESSION[uid]', '$currentTime', '1', '$fran', '$subFran')";

            if ($con->query($sql) === TRUE) {
                ?>
<script>
alert('Document uploaded and data saved successfully.');
setTimeout(() => {
    window.location =
        'view-documents.php?product_id=<?php echo $product_id;?>';
}, 1200);
</script>
<?php
            } else {
                ?>
<script>
alert('<?php echo "Error: " . $sql . "<br>" . $con->error;?>');
setTimeout(() => {
    window.location =
        'view-documents.php?product_id=<?php echo $product_id;?>';
}, 1200);
</script>
<?php
            }
        } else {
            ?>
<script>
alert('File type not allowed. Please upload a valid document.');
setTimeout(() => {
    window.location =
        'view-documents.php?product_id=<?php echo $product_id;?>';
}, 1200);
</script>
<?php
        }
    } else {
        ?>
<script>
alert('Please select a document to upload.');
setTimeout(() => {
    window.location =
        'view-documents.php?product_id=<?php echo $product_id;?>';
}, 1200);
</script>
<?php
    }
}

// Function to compress images
function compressImage($source, $destination, $quality) {
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
        imagejpeg($image, $destination, $quality);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
        imagepng($image, $destination, round($quality / 10)); // PNG compression scale is different
    }
}
?>

<?php
if (isset($_POST['edit_doc'])) {
// Fetch form inputs
$dTitle = mysqli_real_escape_string($con, $_POST['dTitle']);
$document = $edit_row["document"]; // Get the old document name

// Handle file upload
if (isset($_FILES['document']['name']) && $_FILES['document']['name'] != '') {
$file_name = $_FILES['document']['name'];
$file_tmp = $_FILES['document']['tmp_name'];
$file_size = $_FILES['document']['size'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

// Allowed file extensions
$allowed_ext = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];

if (in_array($file_ext, $allowed_ext)) {
// Create unique file name
$new_file_name = uniqid() . '.' . $file_ext;

// File upload path
$upload_dir = "../upload/documents/";
$upload_file = $upload_dir . $new_file_name;

// Compress the image if it's jpg/jpeg/png (optional for other file types)
if (in_array($file_ext, ['jpg', 'jpeg', 'png'])) {
compressImage($file_tmp, $upload_file, 75); // Compress image and upload
} else {
move_uploaded_file($file_tmp, $upload_file); // Directly upload other file types
}

// Delete the old file if it exists
if (file_exists($upload_dir . $document)) {
unlink($upload_dir . $document);
}

// Update the document in the database
$sql = "UPDATE documents SET dTitle='$dTitle', document='$new_file_name' WHERE did='$edit_row[did]'";

if ($con->query($sql) === TRUE) {
?>
<script>
alert('Document updated successfully.');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $product_id; ?>';
}, 1200);
</script>
<?php
            } else {
                ?>
<script>
alert('Error updating record: <?php echo $con->error; ?>');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $product_id; ?>';
}, 1200);
</script>
<?php
            }
        } else {
            ?>
<script>
alert('File type not allowed. Please upload a valid document.');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $product_id; ?>';
}, 1200);
</script>
<?php
        }
    } else {
        // If no new file is uploaded, just update the title
        $sql = "UPDATE documents SET dTitle='$dTitle' WHERE did='$edit_row[did]'";

        if ($con->query($sql) === TRUE) {
            ?>
<script>
alert('Document title updated successfully.');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $product_id; ?>';
}, 1200);
</script>
<?php
        } else {
            ?>
<script>
alert('Error updating record: <?php echo $con->error; ?>');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $product_id; ?>';
}, 1200);
</script>
<?php
        }
    }
}

?>
<?php
// Check if del_id is present in the URL
if (isset($_GET['del_id'])) {
    $del_id = mysqli_real_escape_string($con, $_GET['del_id']);
    
    // Fetch the document file name from the database
    $query = "SELECT document FROM documents WHERE did = '$del_id'";
    $result = mysqli_query($con, $query);
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $document = $row['document'];
        $document_path = "../upload/documents/" . $document;
        
        // Delete the file from the server
        if (file_exists($document_path)) {
            unlink($document_path);
        }
        
        // Delete the record from the database
        $delete_query = "DELETE FROM documents WHERE did = '$del_id'";
        if (mysqli_query($con, $delete_query)) {
            ?>
<script>
alert('Document deleted successfully.');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $_GET['product_id']; ?>';
}, 1200);
</script>
<?php
        } else {
            ?>
<script>
alert('Error deleting document from the database.');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $_GET['product_id']; ?>';
}, 1200);
</script>
<?php
        }
    } else {
        ?>
<script>
alert('Document not found.');
setTimeout(() => {
    window.location = 'view-documents.php?product_id=<?php echo $_GET['product_id']; ?>';
}, 1200);
</script>
<?php
    }
}
?>