<?php
require_once __DIR__ . '/config/config.php';
require_permission('accounting.coa_manage');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code = trim($_POST['account_code'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    $typeId = $_POST['account_type_id'] ?? '';
    $id = $_POST['id'] ?? null;

    if ($code === '' || $desc === '' || !$typeId) {
        flash('error', 'Account code, description, and type are all required.');
    } elseif ($id) {
        $pdo->prepare("UPDATE chart_of_accounts SET account_code=?, description=?, account_type_id=? WHERE id=?")
            ->execute([$code, $desc, $typeId, $id]);
        flash('success', 'Account updated.');
    } else {
        try {
            $pdo->prepare("INSERT INTO chart_of_accounts (account_code, description, account_type_id) VALUES (?,?,?)")
                ->execute([$code, $desc, $typeId]);
            flash('success', 'Account added.');
        } catch (PDOException $ex) {
            flash('error', 'That account code already exists.');
        }
    }
    redirect('chart_of_accounts.php');
}

if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE chart_of_accounts SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    redirect('chart_of_accounts.php');
}

$edit = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM chart_of_accounts WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $edit = $stmt->fetch();
}

$accountTypes = $pdo->query("SELECT * FROM account_types ORDER BY sort_order")->fetchAll();
$accounts = get_chart_of_accounts($pdo, false);

$pageTitle = 'Chart of Accounts';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Chart of Accounts</h1>

<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
  <div class="md:col-span-1 bg-white rounded-xl shadow-sm border border-slate-200 p-5 h-fit">
    <h2 class="font-semibold mb-4"><?= $edit ? 'Edit' : 'Add' ?> Account</h2>
    <form method="POST" class="space-y-3">
      <?php if ($edit): ?><input type="hidden" name="id" value="<?= $edit['id'] ?>"><?php endif; ?>
      <div>
        <label class="text-xs text-slate-500 block mb-1">Account Code</label>
        <input name="account_code" required value="<?= e($edit['account_code'] ?? '') ?>" placeholder="e.g. 40100" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      </div>
      <div>
        <label class="text-xs text-slate-500 block mb-1">Description</label>
        <input name="description" required value="<?= e($edit['description'] ?? '') ?>" placeholder="e.g. Income Room" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      </div>
      <div>
        <label class="text-xs text-slate-500 block mb-1">Account Type</label>
        <select name="account_type_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
          <option value="">-- Select type --</option>
          <?php foreach ($accountTypes as $t): ?>
            <option value="<?= $t['id'] ?>" <?= ($edit['account_type_id'] ?? null)==$t['id']?'selected':'' ?>><?= e($t['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg w-full">
        <?= $edit ? 'Update' : 'Add' ?> Account
      </button>
      <?php if ($edit): ?><a href="chart_of_accounts.php" class="block text-center text-sm text-slate-500">Cancel</a><?php endif; ?>
    </form>
  </div>

  <div class="md:col-span-2 overflow-x-auto">
  <div class="bg-white rounded-xl shadow-sm border border-slate-200">
    <table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
        <th class="text-left px-5 py-2">Code</th><th class="text-left px-5 py-2">Description</th>
        <th class="text-left px-5 py-2">Type</th><th class="text-left px-5 py-2">Classification</th>
        <th class="text-left px-5 py-2">Status</th><th class="text-right px-5 py-2">Actions</th></tr></thead>
      <tbody>
      <?php foreach ($accounts as $a): ?>
        <tr class="border-t border-slate-100">
          <td class="px-5 py-2.5 font-mono text-xs"><?= e($a['account_code']) ?></td>
          <td class="px-5 py-2.5"><?= e($a['description']) ?></td>
          <td class="px-5 py-2.5"><?= e($a['type_name']) ?></td>
          <td class="px-5 py-2.5 capitalize text-slate-500"><?= e($a['classification']) ?></td>
          <td class="px-5 py-2.5">
            <span class="px-2 py-0.5 rounded-full text-xs <?= $a['is_active'] ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-200 text-slate-500' ?>">
              <?= $a['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
          </td>
          <td class="px-5 py-2.5 text-right space-x-3">
            <a href="?edit=<?= $a['id'] ?>" class="text-blue-600 hover:underline">Edit</a>
            <a href="?toggle=<?= $a['id'] ?>" class="text-slate-500 hover:underline"><?= $a['is_active'] ? 'Deactivate' : 'Activate' ?></a>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($accounts)): ?><tr><td colspan="6" class="px-5 py-6 text-center text-slate-400">No accounts yet.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
