<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
include '../db.php';

$id = intval($_GET['id'] ?? 0);

// Fetch existing review
$stmt = $pdo->prepare("
    SELECT r.*, u.username, c.name AS company_name 
    FROM reviews r
    JOIN users u ON r.user_id = u.id
    JOIN companies c ON r.company_id = c.id
    WHERE r.id = ?
");
$stmt->execute([$id]);
$review = $stmt->fetch();

if (!$review) {
    die('Review not found!');
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $comment = trim($_POST['comment']);
    $rating = intval($_POST['rating']);
    if ($rating < 1) $rating = 1;
    if ($rating > 5) $rating = 5;

    $update = $pdo->prepare("UPDATE reviews SET comment=?, rating=? WHERE id=?");
    $update->execute([$comment, $rating, $id]);

    header('Location: manage_review.php?success=1');
    exit;
}
?>

<?php include 'menu.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Review</title>
    <link rel="stylesheet" href="../style.css">
    <style>
        .container { max-width: 500px; margin: 2rem auto; }
        label { font-weight: bold; margin-top: 0.5rem; }
        textarea, input[type="number"] { width: 100%; padding: 0.5rem; margin-bottom: 1rem; }
        button { padding: 0.6rem; background: #007BFF; color: #fff; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>
<div class="container">
    <h2>Edit Review #<?php echo $review['id']; ?></h2>
    <p>User: <strong><?php echo htmlspecialchars($review['username']); ?></strong></p>
    <p>Company: <strong><?php echo htmlspecialchars($review['company_name']); ?></strong></p>

    <form method="post">
        <label>Comment:</label>
        <textarea name="comment" rows="5" required><?php echo htmlspecialchars($review['comment']); ?></textarea>

        <label>Rating (1-5):</label>
        <input type="number" name="rating" value="<?php echo $review['rating']; ?>" min="1" max="5" required>

        <button type="submit">Update Review</button>
    </form>
    <p><a href="manage_review.php">← Back to Reviews</a></p>
</div>
</body>
</html>
