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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $contact = trim($_POST['contact_person'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $id = $_POST['id'] ?? null;

    if ($name === '') {
        flash('error', 'Customer name is required.');
    } elseif ($id) {
        $pdo->prepare("UPDATE ar_customers SET name=?, contact_person=?, phone=?, email=?, address=? WHERE id=?")
            ->execute([$name, $contact, $phone, $email, $address, $id]);
        flash('success', 'Customer updated.');
    } else {
        $pdo->prepare("INSERT INTO ar_customers (name, contact_person, phone, email, address) VALUES (?,?,?,?,?)")
            ->execute([$name, $contact, $phone, $email, $address]);
        flash('success', 'Customer added.');
    }
    redirect('accounts_receivable/customers.php');
}

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

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

$customers = $pdo->query("SELECT * FROM ar_customers ORDER BY name")->fetchAll();

$pageTitle = 'AR Customers';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Accounts Receivable — Customers</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' ?> Customer</h2>
    <form method="POST" class="space-y-3">
      <?php if ($edit): ?><input type="hidden" name="id" value="<?= $edit['id'] ?>"><?php endif; ?>
      <input name="name" required placeholder="Customer / company name" value="<?= e($edit['name'] ?? '') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <input name="contact_person" placeholder="Contact person" value="<?= e($edit['contact_person'] ?? '') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <input name="phone" placeholder="Phone" value="<?= e($edit['phone'] ?? '') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <input name="email" placeholder="Email" value="<?= e($edit['email'] ?? '') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <textarea name="address" placeholder="Address" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm"><?= e($edit['address'] ?? '') ?></textarea>
      <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' ?>
      </button>
      <?php if ($edit): ?><a href="customers.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">Name</th><th class="text-left px-5 py-2">Contact</th>
        <th class="text-left px-5 py-2">Phone</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 ($customers as $c): ?>
        <tr class="border-t border-slate-100">
          <td class="px-5 py-2.5"><?= e($c['name']) ?></td>
          <td class="px-5 py-2.5"><?= e($c['contact_person']) ?></td>
          <td class="px-5 py-2.5"><?= e($c['phone']) ?></td>
          <td class="px-5 py-2.5">
            <span class="px-2 py-0.5 rounded-full text-xs <?= $c['is_active'] ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-200 text-slate-500' ?>">
              <?= $c['is_active'] ? 'Active' : 'Inactive' ?>
            </span>
          </td>
          <td class="px-5 py-2.5 text-right space-x-3">
            <a href="?edit=<?= $c['id'] ?>" class="text-blue-600 hover:underline">Edit</a>
            <a href="?toggle=<?= $c['id'] ?>" class="text-slate-500 hover:underline"><?= $c['is_active'] ? 'Deactivate' : 'Activate' ?></a>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($customers)): ?><tr><td colspan="5" class="px-5 py-6 text-center text-slate-400">No customers yet.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
