<?php
session_start();
include('../../includes/config.php');
include('../../includes/header.php');

// Restrict access to Admins (1) and Accountants (4) only
if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1,4])) {
    header("Location: ../../index.php");
    exit;
}

$errors = [];
$success = '';

$allowed_account_types = ['bank', 'mobile', 'cash', 'other'];

// Handle Create / Update POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $account_code = trim($_POST['account_code'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');
    $account_type = trim($_POST['account_type'] ?? '');
    $bank_name = trim($_POST['bank_name'] ?? '');
    $account_number = trim($_POST['account_number'] ?? '');

    if ($account_code === '') $errors[] = "Account code is required.";
    if ($account_name === '') $errors[] = "Account name is required.";
    if (!in_array($account_type, $allowed_account_types)) $errors[] = "Invalid account type selected.";

    if ($account_type === 'bank') {
        if ($bank_name === '') $errors[] = "Bank name is required for bank accounts.";
        if ($account_number === '') $errors[] = "Account number is required for bank accounts.";
    }

    if (empty($errors)) {
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE accounts SET account_code = ?, account_name = ?, account_type = ?, bank_name = ?, account_number = ?, updated_at = NOW() WHERE id = ?");
            $stmt->bind_param("sssssi", $account_code, $account_name, $account_type, $bank_name, $account_number, $id);
            if ($stmt->execute()) {
                $success = "Account updated successfully.";
            } else {
                $errors[] = "Database error: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $check = $conn->prepare("SELECT COUNT(*) FROM accounts WHERE account_code = ? OR account_name = ?");
            $check->bind_param("ss", $account_code, $account_name);
            $check->execute();
            $check->bind_result($count);
            $check->fetch();
            $check->close();

            if ($count > 0) {
                $errors[] = "Account code or name already exists.";
            } else {
                $stmt = $conn->prepare("INSERT INTO accounts (account_code, account_name, account_type, bank_name, account_number, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
                $stmt->bind_param("sssss", $account_code, $account_name, $account_type, $bank_name, $account_number);
                if ($stmt->execute()) {
                    $success = "Account created successfully.";
                } else {
                    $errors[] = "Database error: " . $stmt->error;
                }
                $stmt->close();
            }
        }
    }
}

// Handle Delete
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM accounts WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $success = "Account deleted successfully.";
    } else {
        $errors[] = "Failed to delete account.";
    }
    $stmt->close();
}

// Fetch accounts
$accounts = [];
$result = $conn->query("SELECT * FROM accounts ORDER BY account_name ASC");
while ($row = $result->fetch_assoc()) {
    $accounts[] = $row;
}
$result->free();

// For editing
$edit_account = null;
if (isset($_GET['edit_id'])) {
    $edit_id = intval($_GET['edit_id']);
    $stmt = $conn->prepare("SELECT * FROM accounts WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $edit_account = $res->fetch_assoc();
    $stmt->close();
}
?>

<style>
body, html {
    margin: 0;
    padding: 0;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: url('../../images/profile.jpg') no-repeat center center fixed;
    background-size: cover;
    color: #eee;
}

.glass-card {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 15px;
    padding: 30px;
    max-width: 900px;
    margin: 40px auto;
    backdrop-filter: blur(12px);
    box-shadow: 0 8px 32px rgba(0,0,0,0.2);
}

.glass-card h2 {
    text-align: center;
    margin-bottom: 20px;
}

input, select {
    width: 100%;
    padding: 10px;
    border-radius: 8px;
    border: none;
    margin-top: 8px;
    font-size: 1rem;
}

button {
    background: #ff6600;
    border: none;
    padding: 10px 20px;
    color: white;
    font-weight: bold;
    border-radius: 6px;
    cursor: pointer;
}

button:hover {
    background: #e65c00;
}

.success, .error {
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 15px;
}

.success {
    background: #44ff44;
    color: #111;
}

.error {
    background: #ff4444;
}

table {
    width: 100%;
    background: rgba(255,255,255,0.08);
    border-collapse: collapse;
    margin-top: 20px;
}

table th, table td {
    padding: 12px;
    border: 1px solid rgba(255,255,255,0.2);
    color: #eee;
}

table th {
    background: rgba(0,0,0,0.3);
}

a.button-link, a.edit-link {
    padding: 6px 12px;
    border-radius: 6px;
    color: #fff;
    text-decoration: none;
    font-weight: bold;
}

a.button-link { background: #dc3545; }
a.button-link:hover { background: #b52b2b; }

a.edit-link { background: #28a745; }
a.edit-link:hover { background: #1e7e34; }
</style>

<div class="glass-card">
    <h2><?= $edit_account ? 'Edit Account' : 'Add New Account' ?></h2>

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

    <?php if ($errors): ?>
        <div class="error"><ul><?php foreach($errors as $e) echo '<li>' . htmlspecialchars($e) . '</li>'; ?></ul></div>
    <?php endif; ?>

    <form method="POST">
        <input type="hidden" name="id" value="<?= htmlspecialchars($edit_account['id'] ?? 0) ?>">

        <label>Account Code</label>
        <input type="text" name="account_code" value="<?= htmlspecialchars($edit_account['account_code'] ?? '') ?>" required>

        <label>Account Name</label>
        <input type="text" name="account_name" value="<?= htmlspecialchars($edit_account['account_name'] ?? '') ?>" required>

        <label>Account Type</label>
        <select name="account_type" id="account_type" onchange="toggleBankFields()" required>
            <option value="">-- Select Type --</option>
            <?php foreach ($allowed_account_types as $type): ?>
                <option value="<?= $type ?>" <?= (isset($edit_account['account_type']) && $edit_account['account_type'] === $type) ? 'selected' : '' ?>>
                    <?= ucfirst($type) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <div id="bank_fields" style="display: none;">
            <label>Bank Name</label>
            <input type="text" name="bank_name" value="<?= htmlspecialchars($edit_account['bank_name'] ?? '') ?>">

            <label>Bank Account Number</label>
            <input type="text" name="account_number" value="<?= htmlspecialchars($edit_account['account_number'] ?? '') ?>">
        </div>

        <button type="submit"><?= $edit_account ? 'Update Account' : 'Add Account' ?></button>
        <?php if($edit_account): ?>
            <a href="accounts_management.php" style="margin-left:10px;">Cancel Edit</a>
        <?php endif; ?>
    </form>

    <h2>All Accounts</h2>
    <table>
        <thead>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th>Type</th>
                <th>Bank</th>
                <th>Number</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!$accounts): ?>
                <tr><td colspan="6" style="text-align:center;">No accounts found.</td></tr>
            <?php else: ?>
                <?php foreach($accounts as $a): ?>
                <tr>
                    <td><?= htmlspecialchars($a['account_code']) ?></td>
                    <td><?= htmlspecialchars($a['account_name']) ?></td>
                    <td><?= ucfirst(htmlspecialchars($a['account_type'])) ?></td>
                    <td><?= htmlspecialchars($a['bank_name']) ?></td>
                    <td><?= htmlspecialchars($a['account_number']) ?></td>
                    <td>
                        <a class="edit-link" href="?edit_id=<?= $a['id'] ?>">Edit</a>
                        <a class="button-link" href="?delete_id=<?= $a['id'] ?>" onclick="return confirm('Are you sure?');">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
function toggleBankFields() {
    var type = document.getElementById('account_type').value;
    document.getElementById('bank_fields').style.display = (type === 'bank') ? 'block' : 'none';
}
document.addEventListener('DOMContentLoaded', toggleBankFields);
</script>

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