<?php
// send_sms_with_all_report_responses.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Assuming 'db_connect.php' and 'sms_api.php' are in the same directory.
// You must ensure 'db_connect.php' contains your actual database connection.
if (!file_exists('db_connect.php')) {
    die("Error: The 'db_connect.php' file was not found. Please ensure it's in the same directory.");
}
if (!file_exists('sms_api.php')) {
    die("Error: The 'sms_api.php' file was not found. Please ensure it's in the same directory.");
}

require_once 'db_connect.php'; // Contains the $conn object
require_once 'sms_api.php';

// Function to fetch the SMS balance from the database
function getLocalSmsBalance($conn) {
    $sql = "SELECT current_balance FROM Kigango_SMS_Balance LIMIT 1";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return (int) $row['current_balance'];
    }
    return 0; // Default to 0 if no record is found
}

// Function to update the SMS balance after a successful send
function updateSmsBalance($conn) {
    // This function now returns the result of the query.
    $sql = "UPDATE Kigango_SMS_Balance SET current_balance = current_balance - 1 WHERE current_balance > 0 LIMIT 1";
    return $conn->query($sql);
}

// Function to log SMS to the database
function logSms($conn, $logData) {
    // Corrected to use a prepared statement to prevent SQL injection and handle all parameters.
    $stmt = $conn->prepare("INSERT INTO SMS_Log (recipient_phone, message_content, sent_status, beem_request_id, api_response, sms_category_id, related_contribution_id, authorized_person_id, partner_id, partner_code, monthYear) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    if ($stmt === false) {
        error_log("Prepare failed: " . $conn->error);
        return false;
    }

    // Correctly bind parameters. 's' for string, 'i' for integer.
    $stmt->bind_param("sssssiisiss",
        $logData['recipient_phone'],
        $logData['message_content'],
        $logData['sent_status'],
        $logData['beem_request_id'],
        $logData['api_response'],
        $logData['sms_category_id'],
        $logData['related_contribution_id'],
        $logData['authorized_person_id'],
        $logData['partner_id'],
        $logData['partner_code'],
        $logData['monthYear']
    );

    $result = $stmt->execute();

    if ($result === false) {
        error_log("Execute failed: " . $stmt->error);
    }

    $stmt->close();
    return $result;
}

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    if ($_POST['action'] === 'send_sms') {
        $recipient_phone = $_POST['recipient_phone'] ?? null;
        $message_content = $_POST['message'] ?? null;
        $sms_category_id = isset($_POST['sms_category_id']) ? intval($_POST['sms_category_id']) : null;
        
        // **Fix 1: Deduct balance before attempting API send**
        $balance = getLocalSmsBalance($conn);
        if ($balance < 1) {
            $response['message'] = "⚠️ Low Balance! Your available SMS balance is **" . $balance . "**. Please recharge to send SMS. For assistance, contact **+255-754-000-000** or use the payment merchant **M-Pesa**.";
            echo json_encode($response);
            exit;
        }

        // **Fix 2: Properly set specific log details for the test SMS**
        $partner_id = null;
        $authorized_person_id = null;
        if ($sms_category_id === 23) {
            $partner_id = 'HP_ADMIN';
            $authorized_person_id = '1';
        }

        // Send the SMS via Beem API
        $send_result = sendBeemSms($recipient_phone, $message_content);

        // Check the status of the API call before proceeding
        if ($send_result['status'] === 'Sent') {
            // **Fix 3: Deduct the balance only on successful API send**
            updateSmsBalance($conn);
            $response['success'] = true;
            $response['message'] = "SMS sent successfully! Current status: **" . $send_result['status'] . "**";
        } else {
            // If API send failed, set the response and do not deduct balance
            $response['success'] = false;
            $response['message'] = "SMS sending failed. Beem API Error: " . ($send_result['error_message'] ?? 'Unknown error.');
        }

        // **Fix 4: Log the SMS regardless of the sending status**
        $logData = [
            'recipient_phone' => $recipient_phone,
            'message_content' => $message_content,
            'sent_status' => $send_result['status'],
            'beem_request_id' => $send_result['beem_request_id'],
            'api_response' => $send_result['api_response'],
            'sms_category_id' => $sms_category_id,
            'related_contribution_id' => null,
            'authorized_person_id' => $authorized_person_id, // This is now correctly handled.
            'partner_id' => $partner_id,
            'partner_code' => null,
            'monthYear' => date('F Y')
        ];

        // Attempt to log the data.
        if (!logSms($conn, $logData)) {
            $response['success'] = false; // Override success if logging fails
            $response['message'] .= "<br>Error: Failed to save SMS record to database.";
        }

        echo json_encode($response);
        exit;
    }
} elseif (isset($_GET['action'])) {

    if ($_GET['action'] === 'get_balance') {
        $balance = getLocalSmsBalance($conn);
        $response['success'] = true;
        $response['balance'] = number_format($balance, 0);
        $response['message'] = '✅ Balance fetched successfully!';
        echo json_encode($response);
        exit;
    }

    if ($_GET['action'] === 'generate_pdf') {
        if (!file_exists('tcpdf/tcpdf_main/tcpdf.php')) {
            die("Error: The TCPDF library file 'tcpdf/tcpdf_main/tcpdf.php' was not found. Please check the path.");
        }
        require_once('tcpdf/tcpdf_main/tcpdf.php');
        
        $sql = "SELECT sl.sms_id, sl.recipient_phone, sl.message_content, sl.sent_status, sl.sent_timestamp, sc.category_name, sl.authorized_person_id AS sent_by
                FROM SMS_Log sl
                LEFT JOIN SMS_Categories sc ON sl.sms_category_id = sc.sms_category_id
                WHERE 1=1";
        
        $where_clauses = [];
        $pdfTitle = "SMS Sent Report";
        $title_details = [];
        
        if (!empty($_GET['search'])) {
            $search = $conn->real_escape_string($_GET['search']);
            $where_clauses[] = "(sl.recipient_phone LIKE '%$search%' OR sl.message_content LIKE '%$search%')";
            $title_details[] = "Recipient: $search";
        }
        
        if (!empty($_GET['group_id'])) {
            $group_id = intval($_GET['group_id']);
            $where_clauses[] = "sl.sms_category_id = $group_id";
            
            $cat_sql = "SELECT category_name FROM SMS_Categories WHERE sms_category_id = $group_id";
            $cat_result = $conn->query($cat_sql);
            if ($cat_result && $cat_result->num_rows > 0) {
                $category_name = $cat_result->fetch_assoc()['category_name'];
                $title_details[] = "Group: $category_name";
            }
        }

        // New: Add SMS status filter to PDF generation
        if (!empty($_GET['status'])) {
            $status = $conn->real_escape_string($_GET['status']);
            $where_clauses[] = "sl.sent_status = '$status'";
            $title_details[] = "Status: " . ucfirst($status);
        }
        
        if (!empty($_GET['start_date']) && !empty($_GET['end_date'])) {
            $start_date = $conn->real_escape_string($_GET['start_date']);
            $end_date = $conn->real_escape_string($_GET['end_date']);
            $where_clauses[] = "DATE(sent_timestamp) BETWEEN '$start_date' AND '$end_date'";
            $title_details[] = "Dates: $start_date to $end_date";
        }
        
        if (!empty($where_clauses)) {
            $sql .= " AND " . implode(" AND ", $where_clauses);
        }

        if (!empty($title_details)) {
            $pdfTitle .= " as per " . implode(", ", $title_details);
        }

        $result = $conn->query($sql);

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('SMS Report');
        $pdf->SetTitle($pdfTitle);
        $pdf->AddPage();
        
        $html = "<h1>" . htmlspecialchars($pdfTitle) . "</h1>";
        $html .= "<table border='1' cellspacing='0' cellpadding='4'>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Recipient</th>
                            <th>Message</th>
                            <th>Status</th>
                            <th>Date/Time</th>
                            <th>Group/Purpose</th>
                            <th>Sent By</th>
                        </tr>
                    </thead>
                    <tbody>";

        $counter = 1;
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $category_name = !empty($row['category_name']) ? htmlspecialchars($row['category_name']) : 'N/A';
                $sent_by = !empty($row['sent_by']) ? htmlspecialchars($row['sent_by']) : '1';
                $html .= "<tr>
                            <td>" . $counter++ . "</td>
                            <td>" . htmlspecialchars($row['recipient_phone']) . "</td>
                            <td>" . htmlspecialchars($row['message_content']) . "</td>
                            <td>" . htmlspecialchars($row['sent_status']) . "</td>
                            <td>" . htmlspecialchars($row['sent_timestamp']) . "</td>
                            <td>" . $category_name . "</td>
                            <td>" . $sent_by . "</td>
                          </tr>";
            }
        } else {
            $html .= "<tr><td colspan='7'>No data found for the selected filters.</td></tr>";
        }

        $html .= "</tbody></table>";
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Output('sms_report.pdf', 'D');
        exit;
    }
}

// All other requests will render the HTML page with the data table.
$category_sql = "SELECT sms_category_id, category_name FROM SMS_Categories ORDER BY category_name";
$categories_result = $conn->query($category_sql);
$categories = [];
if ($categories_result && $categories_result->num_rows > 0) {
    while($row = $categories_result->fetch_assoc()){
        $categories[] = $row;
    }
}

$items_per_page = 50;
$current_page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($current_page - 1) * $items_per_page;

$sql = "SELECT sl.sms_id, sl.recipient_phone, sl.message_content, sl.sent_status, sl.sent_timestamp, sc.category_name, sl.authorized_person_id AS sent_by
        FROM SMS_Log sl
        LEFT JOIN SMS_Categories sc ON sl.sms_category_id = sc.sms_category_id
        WHERE 1=1";

$count_sql = "SELECT COUNT(*) FROM SMS_Log sl WHERE 1=1";

$where_clauses = [];
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = $conn->real_escape_string($_GET['search']);
    $where_clauses[] = "(sl.recipient_phone LIKE '%$search%' OR sl.message_content LIKE '%$search%')";
}
if (isset($_GET['group_id']) && $_GET['group_id'] !== '') {
    $group_id = intval($_GET['group_id']);
    $where_clauses[] = "sl.sms_category_id = $group_id";
}
if (isset($_GET['status']) && $_GET['status'] !== '') {
    $status = $conn->real_escape_string($_GET['status']);
    $where_clauses[] = "sl.sent_status = '$status'";
}
if (isset($_GET['start_date']) && !empty($_GET['start_date'])) {
    $start_date = $conn->real_escape_string($_GET['start_date']);
    $where_clauses[] = "DATE(sl.sent_timestamp) >= '$start_date'";
}
if (isset($_GET['end_date']) && !empty($_GET['end_date'])) {
    $end_date = $conn->real_escape_string($_GET['end_date']);
    $where_clauses[] = "DATE(sl.sent_timestamp) <= '$end_date'";
}

if (!empty($where_clauses)) {
    $sql .= " AND " . implode(" AND ", $where_clauses);
    $count_sql .= " AND " . implode(" AND ", $where_clauses);
}

$sql .= " ORDER BY sl.sent_timestamp DESC LIMIT $items_per_page OFFSET $offset";

$count_result = $conn->query($count_sql);
$total_items = $count_result->fetch_row()[0];
$total_pages = ceil($total_items / $items_per_page);

$result = $conn->query($sql);
$sms_records = [];
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $sms_records[] = $row;
    }
}

$conn->close();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS Sent History</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .icon-small { font-size: 0.8em; }
        .text-pending { color: #ffc107; }
        .text-sent { color: #0dcaf0; }
        .text-delivered { color: #198754; }
        .text-failed { color: #dc3545; }
    </style>
</head>
<body>
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <h2 class="mb-4">SMS Management System</h2>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card bg-light">
                <div class="card-body">
                    <h5 class="card-title">Available SMS Balance 📥</h5>
                    <p class="card-text fs-4 fw-bold" id="smsBalanceDisplay">Fetching...</p>
                    <div id="balanceMessage" class="mt-2 small text-muted"></div>
                    <button class="btn btn-sm btn-outline-primary mt-2" id="refreshBalance"><i class="fas fa-sync-alt"></i> Refresh Balance</button>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card bg-light">
                <div class="card-body">
                    <h5 class="card-title">Send a Test SMS 🧪</h5>
                    <p class="card-text">Quickly test the system with a pre-defined message.</p>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#testSmsModal">
                        <i class="fas fa-paper-plane"></i> Test SMS
                    </button>
                </div>
            </div>
        </div>
    </div>

    <hr>

    <div class="row">
        <div class="col-12">
            <h3 class="mb-3">SMS Sent History 📜</h3>
            <div class="card p-3 mb-3 shadow-sm">
                <form id="filterForm" class="row g-3 align-items-end">
                    <div class="col-md-3">
                        <label for="search" class="form-label">Search</label>
                        <input type="text" class="form-control" id="search" name="search" placeholder="Recipient, message content...">
                    </div>
                    <div class="col-md-2">
                        <label for="group" class="form-label">Group/Purpose</label>
                        <select class="form-select" id="group" name="group_id">
                            <option value="">All</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['sms_category_id']; ?>"><?php echo htmlspecialchars($cat['category_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="status" class="form-label">Status</label>
                        <select class="form-select" id="status" name="status">
                            <option value="">All</option>
                            <option value="Delivered">Delivered</option>
                            <option value="Sent">Sent</option>
                            <option value="Failed">Failed</option>
                            <option value="Pending">Pending</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="start_date" class="form-label">From Date</label>
                        <input type="date" class="form-control" id="start_date" name="start_date">
                    </div>
                    <div class="col-md-2">
                        <label for="end_date" class="form-label">To Date</label>
                        <input type="date" class="form-control" id="end_date" name="end_date">
                    </div>
                    <div class="col-md-1 d-flex justify-content-end">
                        <button type="submit" class="btn btn-success me-2"><i class="fas fa-filter"></i> Filter</button>
                    </div>
                    <div class="col-md-12 text-end mt-2">
                        <button type="button" id="downloadPdfBtn" class="btn btn-danger"><i class="fas fa-file-pdf"></i> PDF</button>
                    </div>
                </form>
            </div>

            <div id="loadingIndicator" class="text-center my-3 d-none">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading SMS records...</p>
            </div>

            <div class="table-responsive">
                <table class="table table-hover table-striped table-bordered">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Recipient</th>
                            <th>Message</th>
                            <th>Status</th>
                            <th>Date/Time</th>
                            <th>Group</th>
                            <th>Sent By (ID)</th>
                        </tr>
                    </thead>
                    <tbody id="smsTableBody">
                        <?php if (count($sms_records) > 0): ?>
                            <?php $index = ($current_page - 1) * $items_per_page + 1; ?>
                            <?php foreach ($sms_records as $record): ?>
                                <tr>
                                    <td><?php echo $index++; ?></td>
                                    <td><?php echo htmlspecialchars($record['recipient_phone']); ?></td>
                                    <td><?php echo htmlspecialchars(substr($record['message_content'], 0, 50)) . '...'; ?></td>
                                    <td>
                                        <span class="badge <?php
                                            switch($record['sent_status']) {
                                                case 'Delivered': echo 'bg-success'; break;
                                                case 'Sent': echo 'bg-info'; break;
                                                case 'Pending': echo 'bg-warning'; break;
                                                case 'Failed': echo 'bg-danger'; break;
                                                default: echo 'bg-secondary';
                                            }
                                        ?>"><?php echo htmlspecialchars($record['sent_status']); ?></span>
                                    </td>
                                    <td><?php echo htmlspecialchars($record['sent_timestamp']); ?></td>
                                    <td><?php echo !empty($record['category_name']) ? htmlspecialchars($record['category_name']) : 'N/A'; ?></td>
                                    <td><?php echo !empty($record['sent_by']) ? htmlspecialchars($record['sent_by']) : '1'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="text-center text-muted">No SMS records found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <nav>
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo ($i === $current_page) ? 'active' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        </div>
    </div>
</div>

<div class="modal fade" id="testSmsModal" tabindex="-1" aria-labelledby="testSmsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="testSmsModalLabel">Send Test SMS</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="testSmsForm">
                    <div class="mb-3">
                        <label for="testPhoneNumber" class="form-label">Phone Number</label>
                        <input type="text" class="form-control" id="testPhoneNumber" name="recipient_phone" required>
                    </div>
                    <div class="mb-3">
                        <label for="testMessage" class="form-label">Message</label>
                        <textarea class="form-control" id="testMessage" rows="3" name="message" readonly>Test SMS</textarea>
                    </div>
                    <input type="hidden" name="action" value="send_sms">
                    <input type="hidden" name="sms_category_id" value="23">
                    <div id="testSmsMessage" class="mt-3"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="sendTestSmsBtn">Send SMS</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="rechargeAlertModal" tabindex="-1" aria-labelledby="rechargeAlertModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="rechargeAlertModalLabel">⚠️ Low SMS Balance!</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Your current SMS balance is **<span id="rechargeBalanceDisplay">0</span>**. You do not have enough SMS to send. Please recharge your account.</p>
        <hr>
        <h6>Recharge Information:</h6>
        <ul>
          <li><strong>Provider Number:</strong> +255-754-000-000</li>
          <li><strong>Payment Merchant:</strong> M-Pesa</li>
        </ul>
        <p class="text-muted small mt-3">For further assistance, please contact the system administrator.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // Function to fetch and display the balance
        function fetchBalance() {
            $.ajax({
                url: 'send_sms_with_all_report_responses.php',
                type: 'GET',
                data: { action: 'get_balance' },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#smsBalanceDisplay').text(response.balance);
                        $('#balanceMessage').html(response.message).removeClass('text-danger').addClass('text-muted');
                    } else {
                        $('#smsBalanceDisplay').text('N/A');
                        $('#balanceMessage').html(response.message).removeClass('text-muted').addClass('text-danger');
                    }
                },
                error: function() {
                    $('#smsBalanceDisplay').text('N/A');
                    $('#balanceMessage').text('Error connecting to the server.').removeClass('text-muted').addClass('text-danger');
                }
            });
        }

        // Initial balance fetch
        fetchBalance();

        // Refresh balance button click
        $('#refreshBalance').on('click', fetchBalance);

        // Handle Test SMS form submission via AJAX
        $('#sendTestSmsBtn').on('click', function() {
            const formData = $('#testSmsForm').serialize();
            const $btn = $(this);
            const originalText = $btn.html();
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Sending...');

            // First, check the balance on the client-side
            const currentBalance = parseInt($('#smsBalanceDisplay').text().replace(/,/g, ''));
            if (currentBalance < 1 || isNaN(currentBalance)) {
                $btn.prop('disabled', false).html(originalText);
                $('#rechargeBalanceDisplay').text(currentBalance || 0);
                const rechargeModal = new bootstrap.Modal(document.getElementById('rechargeAlertModal'));
                rechargeModal.show();
                return;
            }

            $.ajax({
                url: 'send_sms_with_all_report_responses.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    $('#testSmsMessage').html('<div class="alert ' + (response.success ? 'alert-success' : 'alert-danger') + '">' + response.message + '</div>');
                    if (response.success) {
                        setTimeout(function() {
                            $('#testSmsModal').modal('hide');
                            location.reload(); // Reload the page to show the new record
                        }, 2000);
                    }
                },
                error: function(xhr, status, error) {
                    console.log("AJAX Error:", xhr.responseText);
                    $('#testSmsMessage').html('<div class="alert alert-danger">An unexpected error occurred. Please try again.</div>');
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalText);
                }
            });
        });

        // Handle PDF download button click
        $('#downloadPdfBtn').on('click', function() {
            const formUrl = new URLSearchParams($('#filterForm').serialize()).toString();
            window.location.href = 'send_sms_with_all_report_responses.php?action=generate_pdf&' + formUrl;
        });

        // Re-submit the form on filter button click
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            const url = '?' + $(this).serialize();
            window.location.href = url;
        });

        // Set the current filter values back into the form fields
        const params = new URLSearchParams(window.location.search);
        params.forEach((value, key) => {
            if ($(`[name="${key}"]`).is(':checkbox')) {
                if (value === 'on') {
                    $(`[name="${key}"]`).prop('checked', true);
                }
            } else {
                $(`[name="${key}"]`).val(value);
            }
        });
    });
</script>
</body>
</html>