<?php
session_start();
$db = new PDO('sqlite:lawsite.db');

if (isset($_POST['login'])) {
    $stmt = $db->prepare("SELECT * FROM admins WHERE username = ?");
    $stmt->execute([$_POST['username']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($admin && password_verify($_POST['password'], $admin['password'])) {
        $_SESSION['admin'] = $admin['username'];
    } else {
        $error = "Invalid login";
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin.php");
    exit;
}

if (!isset($_SESSION['admin'])) {
    ?>
    <?php include "head.php"; ?>
    <h2>Admin Login</h2>
    <?php if (isset($error)) echo "<p>$error</p>"; ?>
    <form method="post">
        <input type="text" name="username" placeholder="Admin Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit" name="login">Login</button>
    </form>
    <?php include "foot.php"; ?>
    <?php
    exit;
}

if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $lawId = intval($_GET['id']);
    if ($action === 'delete') {
        $db->prepare("DELETE FROM laws WHERE id = ?")->execute([$lawId]);
    } elseif ($action === 'pass') {
        $db->prepare("UPDATE laws SET status='Passed', admin=? WHERE id=?")->execute([$_SESSION['admin'], $lawId]);
    } elseif ($action === 'fail') {
        $db->prepare("UPDATE laws SET status='Failed', admin=? WHERE id=?")->execute([$_SESSION['admin'], $lawId]);
    }
    header("Location: admin.php");
    exit;
}

$laws = $db->query("SELECT * FROM laws ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
include "head.php";
?>
<h2>Admin Panel</h2>
<p>Logged in as <?= htmlspecialchars($_SESSION['admin']) ?> | <a style="color: white" href="?logout=1">Logout</a></p>
<table>
    <tr>
        <th>Title</th>
        <th>Proposer</th>
        <th>Status</th>
        <th>Actions</th>
    </tr>
    <?php foreach ($laws as $law): ?>
    <tr>
        <td><?= htmlspecialchars($law['title']) ?></td>
        <td><?= htmlspecialchars($law['proposer']) ?></td>
        <td><?= htmlspecialchars($law['status']) ?></td>
        <td style="color: white" class="admin-actions">
            <a href="?action=pass&id=<?= $law['id'] ?>">Pass</a>
            <a href="?action=fail&id=<?= $law['id'] ?>">Fail</a>
            <a href="?action=delete&id=<?= $law['id'] ?>" onclick="return confirm('Are you sure?')">Delete</a>
        </td>
    </tr>
    <?php endforeach; ?>
</table>
<?php include "foot.php"; ?>
