<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    header("Location: ../../index.php");
    exit();
}
include('../../includes/config.php');
include('../../includes/header.php');

// Handle deletion
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM accounts WHERE id = $id");
    header("Location: chart_of_accounts.php?msg=Deleted");
    exit();
}

// Fetch accounts
$accounts = $conn->query("SELECT * FROM accounts ORDER BY account_type, account_code");
?>

<style>
body {
    background: url('../../images/profile.jpg') center/cover fixed;
    font-family: 'Segoe UI', sans-serif;
    color: #eee;
}
.wrap {
    max-width: 1300px;
    margin: 100px auto 30px;
    padding: 0 30px;
}
h2 {
    color: #ffa500;
    margin-bottom: 20px;
}
a.btn {
    color: #ffa500;
    font-weight: bold;
    text-decoration: none;
    margin-right: 10px;
}
.table-card {
    background: rgba(255,255,255,0.1);
    border-radius: 15px;
    padding: 20px;
    overflow-x: auto;
}
table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}
th, td {
    padding: 10px 12px;
    border-bottom: 1px solid rgba(255,255,255,0.15);
}
th {
    background: rgba(255,165,0,0.25);
    color: #fff;
}
</style>

<div class="wrap">
    <h2>Chart of Accounts</h2>
    <a href="account_create.php" class="btn">+ New Account</a>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th>Code</th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Bank</th>
                    <th>Account #</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($a = $accounts->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($a['account_code']) ?></td>
                    <td><?= htmlspecialchars($a['account_name']) ?></td>
                    <td><?= ucfirst($a['account_type']) ?></td>
                    <td><?= htmlspecialchars($a['bank_name']) ?></td>
                    <td><?= htmlspecialchars($a['account_number']) ?></td>
                    <td>
                        <a class="btn" href="account_edit.php?id=<?= $a['id'] ?>">Edit</a>
                        <a class="btn" href="?delete=<?= $a['id'] ?>" onclick="return confirm('Delete this account?')">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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