<?php
session_start();
include_once('../includes/db.php');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = trim($_POST['terms'] ?? '');
    $exists = fetchOne("SELECT id FROM terms LIMIT 1");

    if ($exists) {
        $stmt = $conn->prepare("UPDATE terms SET content = ? WHERE id = ?");
        $stmt->bind_param("si", $content, $exists['id']);
        $stmt->execute();
        $stmt->close();
        $message = "✅ Terms updated successfully.";
    } else {
        $stmt = $conn->prepare("INSERT INTO terms (content) VALUES (?)");
        $stmt->bind_param("s", $content);
        $stmt->execute();
        $stmt->close();
        $message = "✅ Terms created successfully.";
    }
}

$current = fetchOne("SELECT content FROM terms LIMIT 1");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Terms & Conditions - PrintShop Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f1f5f9;
        }

        .main-content {
            margin-left: 250px;
            padding: 30px;
        }

        .card {
            border-radius: 1rem;
        }

        textarea {
            font-size: 16px;
            line-height: 1.6;
        }
    </style>
</head>
<body>

<div class="d-flex">
    <?php include('admin_sidebar.php'); ?>

    <div class="main-content flex-grow-1">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-dark text-white rounded-top">
                <h5 class="mb-0">📄 Manage Terms & Conditions</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($message)): ?>
                    <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
                <?php endif; ?>

                <form method="POST">
                    <div class="mb-3">
                        <label for="terms" class="form-label">Terms Content</label>
                        <textarea name="terms" id="terms" rows="12" class="form-control" required><?= htmlspecialchars($current['content'] ?? '') ?></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Save Terms</button>
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>
