<?php
session_start();
require_once "../../config/web_mysqlconnect.php";

function getUserName($id) {
    global $db, $link;
    // SQL query to select AtxUserName from uniuserprofile where AtxUserID is the provided ID
    $q = "SELECT AtxUserName FROM $db.uniuserprofile WHERE AtxUserID='$id'";
    // Execute the query
    $res = mysqli_query($link, $q);
    // Check if there are rows in the result set
    if ($res && mysqli_num_rows($res) > 0) {
        // Fetch the result as an associative array
        $rs = mysqli_fetch_assoc($res);
        // Retrieve the AtxUserName from the result set
        $output = $rs['AtxUserName'];
    } else {
        // Set a default value if no result is found
        $output = " ";
    }
    // Return the username
    return $output;
}

// Simulated login (replace this with your real login/session)
$currentUser = $_SESSION['userid'];
$action = $_POST['action'] ?? '';

if ($action === 'insert') {
    $name = $link->real_escape_string($_POST['name']);
    $content = $link->real_escape_string($_POST['content']);
    $sql = "INSERT INTO reply_templates (template_name, template_content, created_by)
            VALUES ('$name', '$content', '$currentUser')";
    echo $link->query($sql) ? "Reply template added successfully" : "Error: " . $link->error;

} elseif ($action === 'update') {
    $id = (int)$_POST['id'];
    // Restrict update to the template's creator
    $check = $link->query("SELECT created_by FROM reply_templates WHERE id=$id");
    $row = $check->fetch_assoc();
    if ($row['created_by'] !== $currentUser) {
        echo "Access denied: You can only edit your own templates.";
        exit;
    }

    $name = $link->real_escape_string($_POST['name']);
    $content = $link->real_escape_string($_POST['content']);
    $sql = "UPDATE reply_templates SET template_name='$name', template_content='$content' WHERE id=$id";
    echo $link->query($sql) ? "Reply template updated successfully" : "Error: " . $link->error;

} elseif ($action === 'delete') {
    $id = (int)$_POST['id'];
    // Restrict delete to the template's creator
    $check = $link->query("SELECT created_by FROM reply_templates WHERE id=$id");
    $row = $check->fetch_assoc();
    if ($row['created_by'] !== $currentUser) {
        echo "Access denied: You can only delete your own templates.";
        exit;
    }

    $sql = "DELETE FROM reply_templates WHERE id=$id";
    echo $link->query($sql) ? "Reply template deleted successfully" : "Error: " . $link->error;

} elseif ($action === 'fetch') {
    // Admins can see all templates; others see only theirs
    if ($currentUser === 'admin') {
        $sql = "SELECT * FROM reply_templates ORDER BY id DESC";
    } else {
        $sql = "SELECT * FROM reply_templates WHERE created_by='$currentUser' ORDER BY id DESC";
    }

    $result = $link->query($sql);
    $output = '';
    $no = 0;
    while ($row = $result->fetch_assoc()) {
        $no ++;
        $username = getUserName($row['created_by']);
        $output .= "<tr>
            <td>{$no}</td>
            <td>{$row['template_name']}</td>
            <td>" . nl2br(htmlspecialchars($row['template_content'])) . "</td>
            <td>{$username}</td>
            <td>
                <a class='editBtn pointer' data-id='{$row['id']}'><i class='fa fa-edit text-success'></i></a>
                <a class='deleteBtn pointer' data-id='{$row['id']}'><i class='fa fa-trash text-danger'></i></a>
            </td>
        </tr>";
    }
    echo $output ?: "<tr><td colspan='5'>No reply templates found</td></tr>";

} elseif ($action === 'get') {
    $id = (int)$_POST['id'];
    $result = $link->query("SELECT * FROM reply_templates WHERE id=$id");
    echo json_encode($result->fetch_assoc());
}

?>
