<?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['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"];

            $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$product_row["pCollege"]}'");
            if($clg_row = mysqli_fetch_assoc($clg_sql)){
                $clg_id = $clg_row["uid"];
                $clg_name = $clg_row["uname"];
            }

            $course_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '{$product_row["product"]}' ");
            while($course_row = mysqli_fetch_assoc($course_sql)){
                $course_name = $course_row["course_name"];
            }
            $cat_sql = mysqli_query($con, "SELECT * FROM clg_course_cat WHERE sl_no = '{$product_row["pCat"]}' ");
            while($cat_row = mysqli_fetch_assoc($cat_sql)){
                $pCat = $cat_row["cat_name"];
            }
        }

        $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 Documents 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-6">
                                    <label for="uploadType">Upload Document Type</label>
                                    <select name="uploadType" class="form-control" id="uploadtype">
                                        <option value="<?php echo $edit_row["dUploadType"];?>">
                                            <?php echo $edit_row["dUploadType"];?></option>
                                        <option value="Uploaded Documents">Uploaded Documents</option>
                                        <option value="New Upload">New Upload</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="title">Edit Document Title</label>
                                    <input type="text" class="form-control" name="dTitle"
                                        value="<?php echo $edit_row['dTitle']; ?>">
                                </div>
                                <div class="col-md-12 d-none" id="preUploaded">
                                    <p class="mb-0">Select The Documents</p>
                                    <div class="row">
                                        <?php
                                            $prevDoc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'Documents' AND data_recycle = '1' AND data_up_for = '$client_id' ORDER BY data_sl_no DESC");
                                            while($prevDoc_row = mysqli_fetch_assoc($prevDoc_sql)){
                                        ?>
                                        <div class="col-md-3 mb-2">
                                            <div class="card">
                                                <div class="card-header d-flex justify-content-center">
                                                    <input class="form-check-input prev-doc-checkbox" type="checkbox"
                                                        name="selectedDocs[]"
                                                        value="<?php echo $prevDoc_row['data_sl_no']; ?>"> &nbsp;
                                                    <?php echo $prevDoc_row["data_title"];?>
                                                </div>
                                                <div class="card-body">
                                                    <img src="<?php echo $prevDoc_row["data_img"];?>" class="img-fluid"
                                                        alt="<?php echo $prevDoc_row["data_title"];?>">
                                                </div>
                                            </div>
                                        </div>
                                        <?php }?>
                                    </div>
                                </div>

                                <div class="col-md-8 d-none" id="newUpload">
                                    <label for="document">Enter Document</label>
                                    <input type="file" class="form-control" name="document"
                                        accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff,.webp,.pdf,.doc,.docx,.xls,.xlsx,.csv">
                                </div>

                                <div class="col-md-12 mt-2" id="docPreview">
                                    <p><strong>Document Preview :</p>
                                    <div>
                                        <?php 
                                        if($edit_row["dUploadType"] == "New Upload"){
                                            $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>';
                                            }
                                        } elseif($edit_row["dUploadType"] == "Uploaded Documents"){
                                            ?>
                                        <div class="row">
                                            <?php 
                                                $doc_list = $edit_row["document"];
                    
                                                // Use the string in the query
                                                $viewDoc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_sl_no IN ($doc_list)");
                                                while($viewDoc_row = mysqli_fetch_assoc($viewDoc_sql)){
                                                    ?>
                                            <div class="col-md-3 mb-2">
                                                <div class="card">
                                                    <div class="card-header text-center">
                                                        <?php echo $viewDoc_row["data_title"];?></div>
                                                    <div class="card-body">
                                                        <?php 
                                                        $document = $viewDoc_row["data_img"];
                                                        $file_ext = strtolower(pathinfo($document, PATHINFO_EXTENSION)); // Get file extension
                                                
                                                        $document_url = $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>
                                                </div>
                                            </div>
                                            <?php
                                                }
                                                ?>
                                        </div>
                                        <?php
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user my-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 text-white">
                                    <i class="fa fa-arrow-left"></i> Back
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["view_id"])){
                    $view_id = $_GET["view_id"];
                    $view_run = mysqli_query($con, "SELECT * FROM documents WHERE did = '$_GET[view_id]'");
                    if($view_row = mysqli_fetch_assoc($view_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 $view_row["dTitle"];?></p>
                        <p><strong>Document Preview :</p>
                        <?php if($view_row["dUploadType"] == "New Upload"){ ?>
                        <div>
                            <?php 
                                $document = $view_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'])) {
                                    // 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 . '" download>Download Word Document</a>';
                                } elseif (in_array($file_ext, ['xls', 'xlsx'])) {
                                    // Provide a link to download Excel document
                                    echo '<a href="' . $document_url . '" download>Download Excel Document</a>';
                                } else {
                                    // Provide a download link for other file types
                                    echo '<a href="' . $document_url . '" download>Download File</a>';
                                }

                                // Add a Download button
                                echo '<br><a href="' . $document_url . '" download class="btn btn-primary mt-2">Download</a>';
                            ?>
                        </div>
                        <?php } elseif($view_row["dUploadType"] == "Uploaded Documents"){ ?>
                        <div class="row">
                            <?php 
                                $doc_list = $view_row["document"];

                                // Use the string in the query
                                $viewDoc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_sl_no IN ($doc_list)");
                                while($viewDoc_row = mysqli_fetch_assoc($viewDoc_sql)){
                            ?>
                            <div class="col-md-3 mb-2">
                                <div class="card">
                                    <div class="card-header text-center"><?php echo $viewDoc_row["data_title"];?></div>
                                    <div class="card-body">
                                        <?php 
                                            $document = $viewDoc_row["data_img"];
                                            $file_ext = strtolower(pathinfo($document, PATHINFO_EXTENSION)); 
        
                                            $document_url = $document; 
        
                                            // 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 . '" download>Download Word Document</a>';
                                            } elseif (in_array($file_ext, ['xls', 'xlsx'])) {
                                                // Provide a link to download Excel document
                                                echo '<a href="' . $document_url . '" download>Download Excel Document</a>';
                                            } else {
                                                // Provide a download link for other file types
                                                echo '<a href="' . $document_url . '" download>Download File</a>';
                                            }

                                            // Add a Download button
                                            echo '<br><a href="' . $document_url . '" download class="btn btn-primary mt-2">Download</a>';
                                        ?>
                                    </div>
                                </div>
                            </div>
                            <?php } ?>
                        </div>
                        <?php } ?>
                        <a href="view-documents.php?product_id=<?php echo $product_id;?>"
                            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_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 $clg_name;?>
                    </h5>
                    <div class="card-body">
                    </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-12 col-12 mt-2 mb-2">
                                <div class="row justify-content-between align-items-center">
                                    <div class="col-md-10 col-12 mb-2 mb-lg-0">
                                        <h5 class="text-gray-800 m-0">Documents List of <span
                                                style="color:orange;"><?php echo $course_name;?></span></h5>
                                    </div>
                                    <div class="col-md-2 text-end">
                                        <button id="toggleButton" class="btn btn-primary btn-sm"
                                            onclick="toggleDiv()">Add Document
                                        </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;">
                                    <form action="" method="post" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-4 mb-2">
                                                <label for="uploadType">Select Upload Type</label>
                                                <select name="uploadType" class="form-control" id="uploadtype">
                                                    <option value="">Select From The List</option>
                                                    <option value="Uploaded Documents">Uploaded Documents</option>
                                                    <option value="New Upload">New Upload</option>
                                                </select>
                                            </div>

                                            <div class="col-md-12 d-none" id="preUploaded">
                                                <p class="mb-0">Select The Documents</p>
                                                <div class="row">
                                                    <?php
                                                        $prevDoc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'Documents' AND data_recycle = '1' AND data_up_for = '$client_id' ORDER BY data_sl_no DESC");
                                                        while($prevDoc_row = mysqli_fetch_assoc($prevDoc_sql)){
                                                    ?>
                                                    <div class="col-md-3 mb-2">
                                                        <div class="card">
                                                            <div class="card-header d-flex justify-content-center">
                                                                <input class="form-check-input prev-doc-checkbox"
                                                                    type="checkbox" name="selectedDocs[]"
                                                                    value="<?php echo $prevDoc_row['data_sl_no']; ?>">
                                                                &nbsp;
                                                                <?php echo $prevDoc_row["data_title"];?>
                                                            </div>
                                                            <div class="card-body">
                                                                <img src="<?php echo $prevDoc_row["data_img"];?>"
                                                                    class="img-fluid"
                                                                    alt="<?php echo $prevDoc_row["data_title"];?>">
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php }?>
                                                </div>
                                            </div>

                                            <div class="col-md-8 d-none" id="newUpload">
                                                <div class="row">
                                                    <div class="col-md-6 mb-2">
                                                        <label for="title">Enter Document Title</label>
                                                        <input type="text" class="form-control" name="dTitle"
                                                            placeholder="Enter Document Title">
                                                    </div>
                                                    <div class="col-md-6 mb-2">
                                                        <label for="document">Enter Document</label>
                                                        <input type="file" class="form-control" name="document">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div>
                                            <button type="submit" class="btn btn-success btn-user my-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 text-white">
                                                <i class="fa fa-arrow-left"></i> Back
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <div class="col-12">
                                <div>
                                    <h5>Uploaded Documents :</h5>
                                    <ol class="p-0">
                                        <?php
                                        // Convert the stored document IDs into an array
                                        $c = 1;
                                        $doc_sql = mysqli_query($con, "SELECT * FROM documents WHERE dClient = '$client_id' AND dProduct = '$_GET[product_id]' ORDER BY did DESC");
                                        while ($doc_row = mysqli_fetch_assoc($doc_sql)) {
                                        ?>
                                        <li class="mb-2 d-flex justify-content-between">
                                            <span><?php echo $c . ") " . $doc_row["dTitle"]; ?></span>
                                            <span>
                                                <a href="view-documents.php?product_id=<?php echo $product_id;?>&view_id=<?php echo $doc_row["did"];?>"
                                                    class="btn btn-primary btn-sm position-relative m-0"><i
                                                        class="fa fa-eye"></i> View
                                                </a>
                                                <a href='view-documents.php?product_id=<?php echo $product_id;?>&edit_id=<?php echo $doc_row["did"];?>'
                                                    class='btn btn-success btn-sm <?php echo $disable;?>'
                                                    title='Click to Edit'><i class='fa fa-edit' aria-hidden='true'></i>
                                                    Re-upload
                                                </a>
                                            </span>
                                        </li>
                                        <?php  $c++; } ?>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <?php } }?>

    <!-- 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';
        }
    }
    document.getElementById('uploadtype').addEventListener('change', function() {
        const selectedValue = this.value;
        const preUploaded = document.getElementById('preUploaded');
        const newUpload = document.getElementById('newUpload');
        const docPreview = document.getElementById('docPreview');

        // Toggle visibility based on selected option
        if (selectedValue === "Uploaded Documents") {
            preUploaded.classList.remove('d-none');
            newUpload.classList.add('d-none');
            docPreview.classList.add('d-none');
        } else if (selectedValue === "New Upload") {
            newUpload.classList.remove('d-none');
            preUploaded.classList.add('d-none');
            docPreview.classList.add('d-none');
        } else {
            // Hide both if no valid option selected
            preUploaded.classList.add('d-none');
            newUpload.classList.add('d-none');
        }
    });
    </script>

</body>

</html>


<?php
if (isset($_POST['submit'])) {
    // Fetch form inputs
    $dTitle = isset($_POST['dTitle']) ? mysqli_real_escape_string($con, $_POST['dTitle']) : '';
    $product_id = $_GET['product_id']; 
    $client_id = $client_id; 
    $clientAdmin = isset($_POST['clientAdmin']) ? $_POST['clientAdmin'] : '';
    $uploadType = isset($_POST['uploadType']) ? $_POST['uploadType'] : ''; // Get upload type from form
    $dReqId = ""; 

    // Determine SubFranchisee
    $subFran = '';
    if ($clientAdmin == $_SESSION["uref_code"]) {
        $subFran = '0';
    } else {
        $admin_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '$clientAdmin'");
        if ($admin_sql && $admin_row = mysqli_fetch_assoc($admin_sql)) {
            $subFran = $admin_row["uid"];
        } else {
            $subFran = '0'; // Default to '0' if query fails
        }
    }

    if ($uploadType === 'Uploaded Documents') {
        // Handle pre-uploaded documents
        if (!empty($_POST['selectedDocs'])) {
            $selectedDocs = implode(',', $_POST['selectedDocs']); // Convert selected docs to a comma-separated string
            $dTitle = 'Previous Uploaded Documents';

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

            if (mysqli_query($con, $sql)) {
                echoSuccessRedirect('Documents selected and saved successfully.', $product_id);
            } else {
                echoErrorRedirect(mysqli_error($con), $product_id);
            }
        } else {
            echoErrorRedirect('No documents selected. Please choose at least one document.', $product_id);
        }
    } elseif ($uploadType === 'New Upload' && isset($_FILES['document']['name']) && $_FILES['document']['name'] != '') {
        // File upload handling
        $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 applicable
            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 (dUploadType, dTitle, document, dProduct, dClient, dUpby, dCreateDate, dRecycle, dFranchiee, dSubFranchiee, dRequiredId) 
                    VALUES ('$uploadType', '$dTitle', '$new_file_name', '$product_id', '$client_id', '{$_SESSION['uid']}', '$currentTime', '1', '$fran', '$subFran', '$dReqId')";

            if (mysqli_query($con, $sql)) {
                echoSuccessRedirect('Document uploaded and data saved successfully.', $product_id);
            } else {
                echoErrorRedirect(mysqli_error($con), $product_id);
            }
        } else {
            echoErrorRedirect('File type not allowed. Please upload a valid document.', $product_id);
        }
    } else {
        echoErrorRedirect('Please select a document to upload.', $product_id);
    }
}

// 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
    }
}

// Helper functions for redirects
function echoSuccessRedirect($message, $product_id) {
    echo "<script>
        alert('$message');
        setTimeout(() => {
            window.location = 'view-documents.php?product_id=$product_id';
        }, 1200);
    </script>";
}

function echoErrorRedirect($error, $product_id) {
    echo "<script>
        alert('$error');
        setTimeout(() => {
            window.location = 'view-documents.php?product_id=$product_id';
        }, 1200);
    </script>";
}
?>

<?php
if (isset($_POST['edit_doc'])) {
    $uploadType = isset($_POST['uploadType']) ? $_POST['uploadType'] : ''; 
    $dTitle = mysqli_real_escape_string($con, $_POST['dTitle']);

    if ($uploadType === 'Uploaded Documents') {
        // Handle pre-uploaded documents
        if (isset($_POST['selectedDocs']) && !empty($_POST['selectedDocs'])) {
            $selectedDocs = implode(',', $_POST['selectedDocs']); 
            $dTitle = 'Previous Uploaded Documents';

            // Insert into database
            $sql = "UPDATE documents SET dUploadType = '$uploadType', dTitle = '$dTitle', document = '$selectedDocs', dCreateDate = '$currentTime' WHERE did='$edit_row[did]'";

            if (mysqli_query($con, $sql)) {
                echoSuccessRedirect('Documents selected and saved successfully.', $product_id);
            } else {
                echoErrorRedirect(mysqli_error($con), $product_id);
            }
        } else {
            echoErrorRedirect('No documents selected. Please select at least one document.', $product_id);
        }
    } elseif ($uploadType === 'New Upload') {
        // File upload handling
        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', 'gif', 'bmp', 'tiff', 'webp', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'csv'];

            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;

                // Move or compress the file
                if (in_array($file_ext, ['jpg', 'jpeg', 'png'])) {
                    compressImage($file_tmp, $upload_file, 75); // Compress image
                } else {
                    move_uploaded_file($file_tmp, $upload_file); // Direct upload
                }

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

                if (mysqli_query($con, $sql)) {
                    echoSuccessRedirect('Document uploaded and data saved successfully.', $product_id);
                } else {
                    echoErrorRedirect(mysqli_error($con), $product_id);
                }
            } else {
                echoErrorRedirect('File type not allowed. Please upload a valid document.', $product_id);
            }
        } else {
            echoErrorRedirect('Please upload a document.', $product_id);
        }
    } else {
        // Update the database
        $sql = "UPDATE documents SET dTitle = '$dTitle', dUploadType = '$uploadType', dCreateDate = '$currentTime' WHERE did='$edit_row[did]'";

        if (mysqli_query($con, $sql)) {
            echoSuccessRedirect('Document uploaded and data saved successfully.', $product_id);
        }
    }
}
?>


<?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
    }
}
?>