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

// Initialize message variables
$message = '';
$message_class = '';

// Initialize variables for form
$selected_categories = [];
$system_tracking_id = '';
$debt_payment_expiry_period = '';
$notification_send_time = '';
$message_prompt = '';

// Fetch existing settings from the database for id=1
$fetch_query = "SELECT * FROM global_message_settings WHERE id = 1";
$result = $conn->query($fetch_query);

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'];
    $message_prompt = $row['message_prompt'];
}

// Handle form submission for insert or update
if (isset($_POST['submit_settings']) && $_POST['submit_settings'] != '') {
    // Sanitize and get user input
    $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']);

    if (empty($selected_categories)) {
        $message = "Please select at least one category.";
        $message_class = "alert-danger";
    } else {
        // Validate input fields
        if (!empty($system_tracking_id) && !empty($debt_payment_expiry_period) && !empty($notification_send_time) && !empty($message_prompt)) {
            $categories_str = implode(',', $selected_categories);

            // Insert or update the settings with id=1
            $save_query = "INSERT INTO global_message_settings (id, category_name, system_tracking_id, debt_payment_expiry_period, notification_send_time, message_prompt)
                           VALUES (1, ?, ?, ?, ?, ?)
                           ON DUPLICATE KEY UPDATE
                           category_name = VALUES(category_name),
                           system_tracking_id = VALUES(system_tracking_id),
                           debt_payment_expiry_period = VALUES(debt_payment_expiry_period),
                           notification_send_time = VALUES(notification_send_time),
                           message_prompt = VALUES(message_prompt)";

            $stmt = $conn->prepare($save_query);
            $stmt->bind_param("ssiss", $categories_str, $system_tracking_id, $debt_payment_expiry_period, $notification_send_time, $message_prompt);

            if ($stmt->execute()) {
                $message = "Settings saved successfully!";
                $message_class = "alert-success";
            } else {
                $message = "Error saving settings: " . $stmt->error;
                $message_class = "alert-danger";
            }
        } else {
            $message = "Please fill in all fields.";
            $message_class = "alert-warning";
        }
    }
}
?>

<div class="content" id="dynamic-content">
    <h2>Settings Page</h2>
    <p class='alert <?php echo $message_class; ?>'><?php echo $message; ?></p>
    <form method="POST" action="">
        <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' : ''; ?> /> Debt Collection Notification<br>
            <input type="checkbox" name="category_name[]" value="Debit Notification" <?php echo (in_array('Debit Notification', $selected_categories)) ? 'checked' : ''; ?> /> Debit Notification
        </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="Enter Days" 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" class="form-control" id="notification_send_time" value="<?php echo htmlspecialchars($notification_send_time); ?>" required />
        </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>
        <button type="submit" name="submit_settings" value="submit" class="btn btn-primary">Save Settings</button>
    </form>
</div>