<?php
include '../../includes/header.php';
require_once __DIR__ . '/../../classes/CreditSales.php';
if (!$auth->isSuperAdmin($_SESSION['user_id'])) { header('Location: /IMS/unauthorized.php'); exit; }
$creditSales = new CreditSales($conn);
$error = '';
$success = '';
try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $owed = round((float)($_POST['amount_owed'] ?? 0), 2);
        $paid = round((float)($_POST['amount_paid'] ?? 0), 2);
        $stmt = $conn->prepare("INSERT INTO creditors (creditor_name, creditor_phone, description, amount_owed, amount_paid, balance, status, created_by) VALUES (:name, :phone, :description, :owed, :paid, :balance, :status, :created_by)");
        $balance = max(0, $owed - $paid);
        $stmt->execute([
            ':name' => trim($_POST['creditor_name'] ?? ''),
            ':phone' => trim($_POST['creditor_phone'] ?? '') ?: null,
            ':description' => trim($_POST['description'] ?? '') ?: null,
            ':owed' => $owed,
            ':paid' => $paid,
            ':balance' => $balance,
            ':status' => $balance <= 0 ? 'settled' : 'open',
            ':created_by' => (int)$_SESSION['user_id'],
        ]);
        $success = 'Creditor recorded.';
    }
} catch (Throwable $e) { $error = $e->getMessage(); }
$creditors = $creditSales->getCreditors();
?>
<div class="container-fluid px-4 mt-4">
    <h1>Creditors</h1>
    <p class="text-muted">Admin-only register for people or suppliers the business owes.</p>
    <?php if ($success): ?><div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
    <div class="card mb-3"><div class="card-body"><form method="post" class="row">
        <div class="col-md-3 mb-2"><input class="form-control" name="creditor_name" placeholder="Creditor name" required></div>
        <div class="col-md-2 mb-2"><input class="form-control" name="creditor_phone" placeholder="Phone"></div>
        <div class="col-md-3 mb-2"><input class="form-control" name="description" placeholder="Description"></div>
        <div class="col-md-2 mb-2"><input type="number" step="0.01" min="0" class="form-control" name="amount_owed" placeholder="Amount owed" required></div>
        <div class="col-md-2 mb-2"><input type="number" step="0.01" min="0" class="form-control" name="amount_paid" placeholder="Paid" value="0"></div>
        <div class="col-md-12"><button class="btn btn-primary">Add Creditor</button></div>
    </form></div></div>
    <div class="card"><div class="card-body table-responsive"><table class="table table-bordered table-sm"><thead><tr><th>Name</th><th>Phone</th><th>Description</th><th>Owed</th><th>Paid</th><th>Balance</th><th>Status</th></tr></thead><tbody>
        <?php foreach ($creditors as $row): ?><tr><td><?php echo htmlspecialchars($row['creditor_name']); ?></td><td><?php echo htmlspecialchars($row['creditor_phone'] ?? ''); ?></td><td><?php echo htmlspecialchars($row['description'] ?? ''); ?></td><td>MWK <?php echo number_format((float)$row['amount_owed'],2); ?></td><td>MWK <?php echo number_format((float)$row['amount_paid'],2); ?></td><td>MWK <?php echo number_format((float)$row['balance'],2); ?></td><td><?php echo htmlspecialchars($row['status']); ?></td></tr><?php endforeach; ?>
        <?php if (!$creditors): ?><tr><td colspan="7" class="text-center text-muted">No creditors recorded.</td></tr><?php endif; ?>
    </tbody></table></div></div>
</div>
<?php include '../../includes/footer.php'; ?>