<?php
require_once 'config/config.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: auth/login.php");
    exit;
}

// تحميل ملف اللغة
$lang_code = $_SESSION['language'] ?? 'english';
require_once __DIR__ . "/languages/{$lang_code}.php";

// حذف عرض
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $conn->prepare("DELETE FROM quotes WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    header("Location: view_quotes.php");
    exit;
}

// جلب العروض
$result = $conn->query("SELECT * FROM quotes ORDER BY id DESC");
?>

<?php include 'header.php'; ?>
<div class="main-content p-4" style="flex:1;">
    <h2 class="mb-4"><?= $lang['saved_quotes'] ?></h2>

    <table class="table table-bordered table-striped align-middle">
        <thead class="table-dark text-center">
            <tr>
                <th width="5%">#</th>
                <th><?= $lang['quote_text'] ?></th>
                <th width="20%"><?= $lang['actions'] ?></th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result && $result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td class="text-center"><?= htmlspecialchars($row['id']) ?></td>
                        <td>
                            <textarea id="quote_<?= $row['id'] ?>" class="form-control" rows="8"><?= htmlspecialchars($row['result_text']) ?></textarea>
                        </td>
                        <td class="text-center">
                            <button class="btn btn-primary btn-sm mb-2" onclick="copyQuote(<?= $row['id'] ?>)">
                                <?= $lang['copy_text'] ?>
                            </button>
                            <br>
                            <a href="view_quotes.php?delete=<?= $row['id'] ?>" 
                               class="btn btn-danger btn-sm"
                               onclick="return confirm('<?= $lang['confirm_delete'] ?>');">
                               <?= $lang['delete'] ?>
                            </a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="3" class="text-center"><?= $lang['no_saved_quotes'] ?></td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
function copyQuote(id) {
    const textarea = document.getElementById("quote_" + id);
    textarea.select();
    textarea.setSelectionRange(0, 99999);
    document.execCommand("copy");
    alert("✅ <?= $lang['copied_successfully'] ?>");
}
</script>

<?php include 'includes/footer.php'; ?>
