<?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');

$success = $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($_POST['account'] as $type => $acct_id) {
        $desc = $_POST['description'][$type] ?? '';
        $stmt = $conn->prepare("
            INSERT INTO system_account_mappings (transaction_type, account_id, description)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE account_id = VALUES(account_id), description = VALUES(description)
        ");
        $stmt->bind_param("sis", $type, $acct_id, $desc);
        if ($stmt->execute()) {
            $success = "Mappings saved successfully.";
        } else {
            $error = "Failed to save mappings.";
        }
        $stmt->close();
    }
}

$existingMappings = [];
$result = $conn->query("SELECT * FROM system_account_mappings");
while ($row = $result->fetch_assoc()) {
    $existingMappings[$row['transaction_type']] = $row;
}

$accounts = [];
$res = $conn->query("SELECT id, CONCAT(account_code, ' - ', account_name) AS display_name FROM accounts ORDER BY account_code");
while ($a = $res->fetch_assoc()) {
    $accounts[$a['id']] = $a['display_name'];
}

$transactionTypes = [
    'sale_income' => 'Sale Income',
    'expense' => 'Expense',
    'deposit' => 'Deposit',
    'withdrawal' => 'Withdrawal',
    'supplier_payment' => 'Supplier Payment',
    'repayment' => 'Loan Repayment',
    'loan' => 'Loan Received',
    'cogs' => 'Cost of Goods Sold',
    'transfer' => 'Transfer',
];
?>

<style>
body {
    background: url('../../images/profile.jpg') center/cover fixed;
    font-family: 'Segoe UI', sans-serif;
    color: #eee;
}
.wrap {
    max-width: 1000px;
    margin: 60px auto;
    background: rgba(255,255,255,0.08);
    border-radius: 15px;
    padding: 30px;
}
h2 {
    color: #ffa500;
}
form {
    margin-top: 20px;
}
table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}
th, td {
    padding: 12px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
}
th {
    background: rgba(255,165,0,0.25);
}
input, select {
    padding: 8px;
    width: 100%;
    border-radius: 8px;
    border: none;
}
button {
    background: #ffa500;
    color: #222;
    padding: 10px 20px;
    border-radius: 8px;
    border: none;
    margin-top: 15px;
    cursor: pointer;
}
.success { color: #5efc82; margin-top: 10px; }
.error { color: #ff6b6b; margin-top: 10px; }
</style>

<div class="wrap">
    <h2>System Account Mappings</h2>

    <?php if ($success): ?><p class="success"><?= htmlspecialchars($success) ?></p><?php endif; ?>
    <?php if ($error): ?><p class="error"><?= htmlspecialchars($error) ?></p><?php endif; ?>

    <form method="POST">
        <table>
            <thead>
                <tr>
                    <th>Transaction Type</th>
                    <th>Mapped Account</th>
                    <th>Description (Optional)</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($transactionTypes as $typeKey => $label): 
                    $mapped = $existingMappings[$typeKey]['account_id'] ?? '';
                    $desc = $existingMappings[$typeKey]['description'] ?? '';
                ?>
                <tr>
                    <td><?= htmlspecialchars($label) ?></td>
                    <td>
                        <select name="account[<?= $typeKey ?>]" required>
                            <option value="">-- Select Account --</option>
                            <?php foreach ($accounts as $acct_id => $acct_name): ?>
                                <option value="<?= $acct_id ?>" <?= ($mapped == $acct_id) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($acct_name) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td>
                        <input type="text" name="description[<?= $typeKey ?>]" value="<?= htmlspecialchars($desc) ?>">
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <button type="submit">Save Mappings</button>
    </form>
</div>

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