<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include necessary files
include "db.php"; // Database connection file
include "commen.php"; // Any additional common functionality

// Check if 'voice_message' column exists, add if not
$column_check = $conn->query("SHOW COLUMNS FROM user_category_message_settings LIKE 'voice_message'");
if ($column_check->num_rows == 0) {
    $conn->query("ALTER TABLE user_category_message_settings ADD voice_message VARCHAR(255) NULL");
}

$column_check_media = $conn->query("SHOW COLUMNS FROM user_category_message_settings LIKE 'media_files'");
if ($column_check_media->num_rows == 0) {
    $conn->query("ALTER TABLE user_category_message_settings ADD media_files TEXT NULL");
}

// Initialize variables
$message = '';
$message_class = '';
$selected_categories = [];
$system_tracking_id = '';
$debt_payment_expiry_period = '';
$notification_send_time = '';
$message_prompt = '';
$media_files = [];
$voice_messages = [];
$notification_times = [];

// Get user_id from request
$user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';

if (!empty($user_id)) {
    $fetch_query = "SELECT * FROM user_category_message_settings WHERE user_id = ?";
    $stmt = $conn->prepare($fetch_query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $selected_categories = explode(',', $row['category_name']);
        $system_tracking_id = $row['system_tracking_id'];
        $debt_payment_expiry_period = $row['debt_payment_expiry_period'];
        $notification_send_time = $row['notification_send_time'];
        $notification_times = !empty($row['notification_times']) ? explode(',', $row['notification_times']) : [];
        $message_prompt = $row['message_prompt'];
        $voice_messages = !empty($row['voice_message']) ? explode(',', $row['voice_message']) : [];
        $media_files = !empty($row['media_files']) ? explode(',', $row['media_files']) : [];
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_settings'])) {
    $selected_categories = isset($_POST['category_name']) ? $_POST['category_name'] : [];
    $system_tracking_id = trim($_POST['system_tracking_id']);
    $debt_payment_expiry_period = (int) trim($_POST['debt_payment_expiry_period']);
    $notification_send_time = trim($_POST['notification_send_time']);
    $message_prompt = trim($_POST['message_prompt']);

    // Initialize an array to hold the file paths
    $media_files = [];

    // Check if files were uploaded
    if (isset($_FILES['media_files']) && count($_FILES['media_files']['name']) > 0) {
        // Loop through each file and upload it
        for ($i = 0; $i < count($_FILES['media_files']['name']); $i++) {
            $file_tmp = $_FILES['media_files']['tmp_name'][$i];
            $file_name = $_FILES['media_files']['name'][$i];
            $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);

            // Define the directory to store the uploaded file
            $upload_dir = 'uploads/media/';
            
            // Generate a unique filename to prevent overwriting
            $unique_file_name = uniqid() . '.' . $file_ext;
            $file_path = $upload_dir . $unique_file_name;

            // Move the file to the uploads directory
            if (move_uploaded_file($file_tmp, $file_path)) {
                // Add the file path to the media_files array
                $media_files[] = $file_path; // You are already storing the full path here
            }
        }
    }

    // If no files were uploaded, set media_files to an empty string
    $media_files_str = !empty($media_files) ? implode(',', $media_files) : '';  // Convert array to comma-separated string

    // Notification times logic (unchanged from your code)
    $notification_times = [];
    if (isset($_POST['hour']) && isset($_POST['minute']) && isset($_POST['ampm'])) {
        for ($i = 0; $i < count($_POST['hour']); $i++) {
            $hour = (int) $_POST['hour'][$i];
            $minute = str_pad((int) $_POST['minute'][$i], 2, '0', STR_PAD_LEFT);
            $ampm = $_POST['ampm'][$i];
            
            if ($ampm == 'PM' && $hour != 12) {
                $hour += 12;
            } elseif ($ampm == 'AM' && $hour == 12) {
                $hour = 0;
            }
            
            $time = str_pad($hour, 2, '0', STR_PAD_LEFT) . ":" . $minute;
            $notification_times[] = $time;
        }
    }
    
    $notification_times_str = !empty($notification_times) ? implode(',', $notification_times) : '';
    
    if (empty($user_id)) {
        $message = "User ID is required.";
        $message_class = "alert-danger";
    } elseif (empty($selected_categories)) {
        $message = "Please select at least one category.";
        $message_class = "alert-danger";
    } else {
        $categories_str = implode(',', $selected_categories);
        
        $check_query = "SELECT user_id FROM user_category_message_settings WHERE user_id = ?";
        $stmt = $conn->prepare($check_query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            // Update query
            $update_query = "UPDATE user_category_message_settings 
                             SET category_name = ?, system_tracking_id = ?, debt_payment_expiry_period = ?, 
                                 notification_send_time = ?, message_prompt = ?, notification_times = ?, 
                                 media_files = ? WHERE user_id = ?";
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("ssisssss", $categories_str, $system_tracking_id, $debt_payment_expiry_period, 
                              $notification_send_time, $message_prompt, $notification_times_str, $media_files_str, $user_id);
            $stmt->execute();
        } else {
            // Insert query
            $insert_query = "INSERT INTO user_category_message_settings (user_id, category_name, system_tracking_id, 
                            debt_payment_expiry_period, notification_send_time, notification_times, message_prompt, media_files) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("ississss", $user_id, $categories_str, $system_tracking_id, $debt_payment_expiry_period, 
                              $notification_send_time, $notification_times_str, $message_prompt, $media_files_str);
            $stmt->execute();
        }

        // Redirect after successful insertion/update
        echo "<script>window.location.href = '{$_SERVER['PHP_SELF']}?user_id={$user_id}';</script>";
        exit;
    }
}
?>

<div class="content" id="dynamic-content">
    <h2><?php echo $user_id ? 'Edit Settings' : 'Add New Settings'; ?></h2>
    <p class='alert <?php echo $message_class; ?>'><?php echo $message; ?></p>
    <form method="POST" action="" enctype="multipart/form-data">
        <div class="mb-3">
            <label class="form-label">Choose Categories</label><br>
            <input type="checkbox" name="category_name[]" value="Debt Collection Notification" <?php echo (in_array('Debt Collection Notification', $selected_categories)) ? 'checked' : ''; ?> />
            <span class="translate-text">Debt Collection Notification</span><br>

            <input type="checkbox" name="category_name[]" value="Debit Notification" <?php echo (in_array('Debit Notification', $selected_categories)) ? 'checked' : ''; ?> />
            <span class="translate-text">Debit Notification</span>
        </div>
        <div class="mb-3">
            <label for="system_tracking_id" class="form-label">System Tracking ID</label>
            <input type="text" name="system_tracking_id" placeholder="Enter System Tracking Id" class="form-control"
                id="system_tracking_id" value="<?php echo htmlspecialchars($system_tracking_id); ?>" required />
        </div>
        <div class="mb-3">
            <label for="debt_payment_expiry_period" class="form-label">Debt Payment Expiry Period (in days)</label>
            <input type="number" name="debt_payment_expiry_period" placeholder="Expiry Period" class="form-control"
                id="debt_payment_expiry_period" value="<?php echo htmlspecialchars($debt_payment_expiry_period); ?>"
                required />
        </div>
        <div class="mb-3">
            <label for="notification_send_time" class="form-label">Notification Send Time</label>
            <input type="number" name="notification_send_time" placeholder="Enter Hours To Send Notification"
                class="form-control" id="notification_send_time"
                value="<?php echo htmlspecialchars($notification_send_time); ?>" required />
        </div>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
        <link rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
        <link rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/css/bootstrap-timepicker.min.css">

        <div class="mb-3">
            <label for="notification_times" class="form-label fw-bold">Notification Times</label>
            <div id="time-input-container" class="p-2 border rounded bg-light">
                <?php foreach ($notification_times as $time): ?>
                    <div class="time-entry d-flex align-items-center mb-2">
                        <div class="input-group">
                            <select class="form-select hour-selector me-1" name="hour[]">
                                <?php for ($h = 1; $h <= 12; $h++): ?>
                                    <option value="<?php echo $h; ?>" <?php echo ($h == date('g', strtotime($time))) ? 'selected' : ''; ?>><?php echo str_pad($h, 2, "0", STR_PAD_LEFT); ?></option>
                                <?php endfor; ?>
                            </select>
                            <span class="input-group-text">:</span>
                            <select class="form-select minute-selector me-1" name="minute[]">
                                <?php for ($m = 0; $m < 60; $m += 1): ?>
                                    <option value="<?php echo $m; ?>" <?php echo ($m == date('i', strtotime($time))) ? 'selected' : ''; ?>><?php echo str_pad($m, 2, "0", STR_PAD_LEFT); ?></option>
                                <?php endfor; ?>
                            </select>
                            <select class="form-select ampm-selector me-2" name="ampm[]">
                                <option value="AM" <?php echo (date('A', strtotime($time)) == 'AM') ? 'selected' : ''; ?>>AM
                                </option>
                                <option value="PM" <?php echo (date('A', strtotime($time)) == 'PM') ? 'selected' : ''; ?>>PM
                                </option>
                            </select>
                            <button type="button" class="btn btn-danger btn-sm remove-time">X</button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="input-group mt-2">
                <select class="form-select hour-selector me-1" id="new-hour">
                    <?php for ($h = 1; $h <= 12; $h++): ?>
                        <option value="<?php echo $h; ?>"><?php echo str_pad($h, 2, "0", STR_PAD_LEFT); ?></option>
                    <?php endfor; ?>
                </select>
                <span class="input-group-text">:</span>
                <select class="form-select minute-selector me-1" id="new-minute">
                    <?php for ($m = 0; $m < 60; $m += 1): ?>
                        <option value="<?php echo $m; ?>"><?php echo str_pad($m, 2, "0", STR_PAD_LEFT); ?></option>
                    <?php endfor; ?>
                </select>
                <select class="form-select ampm-selector me-2" id="new-ampm">
                    <option value="AM">AM</option>
                    <option value="PM">PM</option>
                </select>
                <button type="button" id="add-time" class="btn btn-primary">Add</button>
            </div>
        </div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <div class="mb-3">
            <label for="media_files" class="form-label fw-bold">Upload Images/Videos</label>
            <input type="file" name="media_files[]" multiple accept="image/*,video/*" class="form-control" />

            <?php if (!empty($media_files)): ?>
                <div class="uploaded-files mt-3 p-3 border rounded shadow-sm bg-light">
                    <h6 class="fw-bold">Previously Uploaded Files:</h6>
                    <ul class="list-group">
                        <?php foreach ($media_files as $file): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <a href="<?php echo $file; ?>" download class="text-decoration-none text-primary">
                                    <?php echo basename($file); ?>
                                </a>
                                <button class="btn btn-danger btn-sm delete-file"
                                    data-file="<?php echo $file; ?>">Delete</button>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
        </div>
        <div class="mb-3">
            <label for="message_prompt" class="form-label">Message</label>
            <textarea name="message_prompt" class="form-control" id="message_prompt"
                required><?php echo htmlspecialchars($message_prompt); ?></textarea>
        </div>
        <div class="mb-3">
            <label for="voice_message" class="form-label fw-bold">Upload Voice Messages (OGG only)</label>
            <input type="file" name="voice_message[]" class="form-control" id="voice_message" accept=".ogg" multiple />

            <!-- Recording Section -->
            <button type="button" id="start-recording" class="btn btn-primary mt-2">Start Recording</button>
            <button type="button" id="stop-recording" class="btn btn-danger mt-2" disabled>Stop Recording</button>
            <audio id="recorded-audio" controls class="mt-2 d-none"></audio>
            <input type="hidden" id="recorded-file" name="recorded_voice" />

            <?php if (!empty($voice_messages)): ?>
                <div class="mt-3 p-3 border rounded shadow-sm bg-light voice-container">
                    <h6 class="fw-bold">Previously Uploaded Voice Messages:</h6>
                    <?php foreach ($voice_messages as $voice_message): ?>
                        <div class="d-flex align-items-center mb-2">
                            <audio controls class="flex-grow-1">
                                <source src="<?php echo htmlspecialchars($voice_message); ?>" type="audio/ogg">
                                Your browser does not support the audio tag.
                            </audio>
                            <button class="btn btn-danger btn-sm ms-2 delete-voice"
                                data-file="<?php echo htmlspecialchars($voice_message); ?>"
                                data-user-id="<?php echo $user_id; ?>">
                                Delete
                            </button>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
                let mediaRecorder;
                let recordedChunks = [];

                const startBtn = document.getElementById("start-recording");
                const stopBtn = document.getElementById("stop-recording");
                const audioPlayer = document.getElementById("recorded-audio");

                // Get user_id from the URL (GET parameter)
                const urlParams = new URLSearchParams(window.location.search);
                const userId = urlParams.get("user_id");

                startBtn.addEventListener("click", async function () {
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                        mediaRecorder = new MediaRecorder(stream);

                        mediaRecorder.ondataavailable = function (event) {
                            if (event.data.size > 0) {
                                recordedChunks.push(event.data);
                            }
                        };

                        mediaRecorder.onstop = function () {
                            const audioBlob = new Blob(recordedChunks, { type: "audio/ogg" });
                            const audioUrl = URL.createObjectURL(audioBlob);
                            audioPlayer.src = audioUrl;
                            audioPlayer.classList.remove("d-none");

                            // Generate timestamped filename
                            const timestamp = Date.now();
                            const file = new File([audioBlob], `${timestamp}.ogg`, { type: "audio/ogg" });

                            // Upload file using FormData
                            const formData = new FormData();
                            formData.append("voice_message", file);
                            formData.append("user_id", userId); // Pass user_id via FormData

                            fetch(`upload-voice.php?user_id=${userId}`, { // Pass user_id via GET
                                method: "POST",
                                body: formData
                            })
                                .then(response => response.text())
                                .then(data => {
                                    console.log("Upload response:", data);
                                })
                                .catch(error => {
                                    console.error("Upload error:", error);
                                });
                        };

                        mediaRecorder.start();
                        startBtn.disabled = true;
                        stopBtn.disabled = false;
                        recordedChunks = [];
                    } catch (error) {
                        console.error("Error accessing microphone:", error);
                    }
                });

                stopBtn.addEventListener("click", function () {
                    mediaRecorder.stop();
                    startBtn.disabled = false;
                    stopBtn.disabled = true;
                });
            });
        </script>

        <button type="submit" name="submit_settings" value="submit"
            class="btn btn-primary"><?php echo $user_id ? 'Update' : 'Submit'; ?></button>
    </form>
</div>

<script>
    $(document).ready(function () {
        // Add new time entry
        $('#add-time').on('click', function () {
            let hour = $('#new-hour').val();
            let minute = $('#new-minute').val();
            let ampm = $('#new-ampm').val();

            let timeEntry = $('<div class="time-entry d-flex align-items-center mb-2">' +
                '<div class="input-group">' +
                '<select class="form-select hour-selector me-1" name="hour[]">' + $("#new-hour").html() + '</select>' +
                '<span class="input-group-text">:</span>' +
                '<select class="form-select minute-selector me-1" name="minute[]">' + $("#new-minute").html() + '</select>' +
                '<select class="form-select ampm-selector me-2" name="ampm[]">' + $("#new-ampm").html() + '</select>' +
                '<button type="button" class="btn btn-danger btn-sm remove-time">X</button>' +
                '</div></div>');

            // Set initial values for the new time entry
            timeEntry.find('.hour-selector').val(hour);
            timeEntry.find('.minute-selector').val(minute);
            timeEntry.find('.ampm-selector').val(ampm);

            $('#time-input-container').append(timeEntry);
        });

        // Remove time entry
        $('#time-input-container').on('click', '.remove-time', function () {
            $(this).closest('.time-entry').remove();
        });

        // Update existing time entry when value is changed
        $('#time-input-container').on('change', '.hour-selector, .minute-selector, .ampm-selector', function () {
            let updatedHour = $(this).closest('.time-entry').find('.hour-selector').val();
            let updatedMinute = $(this).closest('.time-entry').find('.minute-selector').val();
            let updatedAmpm = $(this).closest('.time-entry').find('.ampm-selector').val();

            // Optionally, you can update a hidden field or store the updated values for further processing
            // For example, update a hidden input or log the changes
            console.log("Updated Time: " + updatedHour + ":" + updatedMinute + " " + updatedAmpm);
        });
    });
</script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll(".delete-file").forEach(button => {
            button.addEventListener("click", function () {
                let filePath = this.getAttribute("data-file");
                let userId = "<?php echo $user_id; ?>"; // Ensure this PHP variable is available in the script
                let listItem = this.closest("li");

                if (confirm("Are you sure you want to delete this file?")) {
                    fetch("delete_file.php", {
                        method: "POST",
                        headers: { "Content-Type": "application/x-www-form-urlencoded" },
                        body: "file=" + encodeURIComponent(filePath) + "&user_id=" + encodeURIComponent(userId)
                    })
                        .then(response => response.text())
                        .then(data => {
                            if (data === "success") {
                                listItem.remove();
                            } else {
                                alert("Failed to delete file.");
                            }
                        });
                }
            });
        });
    });
</script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll(".delete-voice").forEach(button => {
            button.addEventListener("click", function () {
                let filePath = this.getAttribute("data-file");
                let userId = this.getAttribute("data-user-id"); // Fix PHP variable issue
                let audioWrapper = this.closest(".voice-container"); // Get parent wrapper

                if (confirm("Are you sure you want to delete this voice message?")) {
                    fetch("delete_voice.php", {
                        method: "POST",
                        headers: { "Content-Type": "application/x-www-form-urlencoded" },
                        body: "file=" + encodeURIComponent(filePath) + "&user_id=" + encodeURIComponent(userId)
                    })
                        .then(response => response.text())
                        .then(data => {
                            if (data.trim() === "success") {
                                button.previousElementSibling.remove(); // Remove audio element
                                button.remove(); // Remove button itself
                            } else {
                                alert("Failed to delete voice message.");
                            }
                        });
                }
            });
        });
    });
</script>