<?php
/**
 * Author: Vastvikta 
 * Date: 23-03-2026 
 * Case Document Configuration
 * This code is used in a web application to manage the configuration for case document uploads, including allowed file types, maximum file size, and upload path. It provides an interface for administrators to enable or disable specific document types and set the upload parameters. The code also includes validation to ensure that the uploaded files meet the specified criteria.
 */

include "../../config/web_mysqlconnect.php";
global $db, $link;

$msg = "";

$docTypeMap = [
    "image" => ["jpg", "jpeg", "png"],
    "pdf"   => ["pdf"],
    "audio" => ["mp3", "wav"],
    "video" => ["mp4", "avi"],
    "docx"  => ["doc", "docx"],
    "Excel" => ["xls", "xlsx"],
    "text"  => ["txt"]
];
// SAVE / UPDATE
if(isset($_POST['save_all'])){

    $statusData = $_POST['status'] ?? [];
    $path = trim($_POST['path']); // remove extra spaces

    // ✅ FIX: ensure leading + trailing slash
    $path = '/' . trim($path, '/') . '/';

    $file_size = $_POST['file_size'] * 1024 * 1024;

    foreach($docTypeMap as $type => $exts){

        $status = isset($statusData[$type]) ? $statusData[$type] : 0;

        foreach($exts as $ext){

            $check = mysqli_query($link, "SELECT * FROM allowed_doc_types WHERE type_name='$ext'");
            
            if(mysqli_num_rows($check) > 0){
                mysqli_query($link, "UPDATE allowed_doc_types 
                    SET status='$status', path='$path', file_size='$file_size' 
                    WHERE type_name='$ext'");
            } else {
                mysqli_query($link, "INSERT INTO allowed_doc_types 
                    (type_name, status, path, file_size) 
                    VALUES ('$ext', '$status', '$path', '$file_size')");
            }
        }
    }

    $msg = "Configuration Updated Successfully!";
}
// FETCH DATA
$typeStatusMap = [];
$currentPath = "/unistorage/omnichannel_config/case_documents/";
$currentSize = 5;

$res = mysqli_query($link, "SELECT * FROM allowed_doc_types");
while($row = mysqli_fetch_assoc($res)){
    $typeStatusMap[$row['type_name']] = $row['status'];
    $currentPath = $row['path'];
    $currentSize = $row['file_size'] / (1024*1024);
}

// GROUP STATUS
$groupStatus = [];
foreach($docTypeMap as $type => $exts){
    $status = 0;
    foreach($exts as $ext){
        if(isset($typeStatusMap[$ext]) && $typeStatusMap[$ext] == 1){
            $status = 1;
            break;
        }
    }
    $groupStatus[$type] = $status;
}
?>

<style>
*, ::after, ::before {
    box-sizing: border-box;
    font-size: 12px;
}
.doc-box {
    font-color: black!important;
    padding: 10px;
    margin: 5px;
    display: inline-block;
    border-radius: 6px;
    border: 2px solid transparent;
    width:100px;
     color: black;
}
.green { border: 2px solid green; }
.red { border: 2px solid #bf0b29; }
</style>

<div class="style2-table">
  <div class="style-title">
    <h3>Document Upload Configuration</h3>

    <?php if (!empty($msg)) echo "<p style='color: green;'>$msg</p>"; ?>

    <form method="post" onsubmit="return checkChanges();">

    <!-- store original values -->
    <input type="hidden" id="old_path" value="<?= $currentPath ?>">
    <input type="hidden" id="old_size" value="<?= $currentSize ?>">

    <table class="table table-bordered main-form">

<tr>
  <td><b>Document Types</b></td>
  <td>

<?php foreach($docTypeMap as $type => $exts): 
    $status = $groupStatus[$type];
    $colorClass = ($status == 1) ? "green" : "red";
?>

<div class="doc-box <?= $colorClass ?>">
    <?= ucfirst($type) ?><br>

    <input type="hidden" class="old-status" value="<?= $status ?>">

    <label>
        <input type="radio" name="status[<?= $type ?>]" value="1" <?= ($status==1?'checked':'') ?>> Active
    </label>

    <label>
        <input type="radio" name="status[<?= $type ?>]" value="0" <?= ($status==0?'checked':'') ?>> Inactive
    </label>
</div>

<?php endforeach; ?>

  </td>
</tr>

<tr>
  <td><b>Upload Path</b></td>
  <td>
    <input type="text" id="path" name="path" value="<?= $currentPath ?>" style="width:300px;">
  </td>
</tr>

<tr>
  <td><b>Max File Size (MB)</b></td>
  <td>
    <input type="number" id="size" name="file_size" min="5" max="20" value="<?= $currentSize ?>"   oninput="checkMaxSize(this)">
  </td>
</tr>

<tr>
  <td colspan="2" align="center">
    <input type="submit" name="save_all" value="Save Configuration" class="button-orange1">
  </td>
</tr>

    </table>
    </form>

  </div>
</div>

<script>
    function checkMaxSize(el){
    if(parseInt(el.value) > 20){
        alert("Max file size cannot be greater than 20 MB");
        el.value = 20;
    }
}
function checkChanges(){
    let changed = false;

    // check status changes
    document.querySelectorAll('.doc-box').forEach(box => {
        let oldStatus = box.querySelector('.old-status').value;
        let radios = box.querySelectorAll("input[type=radio]");
        let selected;

        radios.forEach(r => { if(r.checked) selected = r.value; });

        if(oldStatus != selected){
            changed = true;
        }
    });

    // check path change
    let oldPath = document.getElementById("old_path").value;
    let newPath = document.getElementById("path").value;

    if(oldPath != newPath){
        changed = true;
    }

    // check size change
    let oldSize = document.getElementById("old_size").value;
    let newSize = document.getElementById("size").value;

    if(oldSize != newSize){
        changed = true;
    }

    if(!changed){
        alert("No changes made!");
        return false;
    }

    return true;
}
</script>