<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('supplier_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'pay') {
    $supplier_id = (int)$_POST['supplier_id'];
    $amount = (float)$_POST['amount'];
    $payment_method = $_POST['payment_method'] ?? 'Cash';
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $note = trim($_POST['note'] ?? '');

    if ($supplier_id <= 0 || $amount <= 0) {
        $_SESSION['error'] = 'Invalid supplier or amount must be greater than zero.';
        header('Location: supplier_payments.php'); exit;
    }

    try {
        $pdo->beginTransaction();

        $payment_no = generatePaymentNo();

        $stmt = $pdo->prepare("INSERT INTO payments (payment_no, payment_type, reference_id, supplier_id, amount, payment_method, payment_date, note, received_by) VALUES (?, 'supplier', 0, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$payment_no, $supplier_id, $amount, $payment_method, $payment_date, $note, $_SESSION['user_id']]);

        $stmt = $pdo->prepare("UPDATE suppliers SET current_balance = current_balance - ? WHERE id = ?");
        $stmt->execute([$amount, $supplier_id]);

        $pdo->commit();
        logActivity('Supplier Payment', 'Suppliers', $supplier_id, "Payment of " . formatCurrency($amount) . " to supplier ID $supplier_id");
        $_SESSION['success'] = "Payment of " . formatCurrency($amount) . " recorded successfully.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = 'Transaction failed: ' . $e->getMessage();
    }
    header('Location: supplier_payments.php'); exit;
}

$payments = $pdo->query("
    SELECT pay.*, s.supplier_name, s.company_name, u.name as received_by_name
    FROM payments pay
    LEFT JOIN suppliers s ON pay.supplier_id = s.id
    LEFT JOIN users u ON pay.received_by = u.id
    WHERE pay.payment_type = 'supplier'
    ORDER BY pay.id DESC
")->fetchAll();

$suppliers = $pdo->query("SELECT id, supplier_name, company_name, current_balance FROM suppliers WHERE status = 1 ORDER BY supplier_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-hand-holding-usd me-2"></i>Supplier Payments</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#paymentModal"><i class="fas fa-plus me-1"></i>New Payment</button>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="supplierPaymentsTable" class="table table-hover datatable">
                        <thead><tr><th>Payment No</th><th>Supplier</th><th>Amount</th><th>Method</th><th>Date</th><th>Note</th><th>Received By</th></tr></thead>
                        <tbody>
                            <?php if (!empty($payments)): ?>
                            <?php foreach ($payments as $p): ?>
                            <tr>
                                <td><code><?= htmlspecialchars($p['payment_no'] ?? '-') ?></code></td>
                                <td><strong><?= htmlspecialchars($p['supplier_name'] ?? $p['company_name'] ?? '-') ?></strong></td>
                                <td><strong><?= formatCurrency($p['amount']) ?></strong></td>
                                <td><span class="badge bg-secondary"><?= htmlspecialchars($p['payment_method']) ?></span></td>
                                <td><?= formatDate($p['payment_date']) ?></td>
                                <td><?= htmlspecialchars($p['note'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($p['received_by_name'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="paymentModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="pay">
                <div class="modal-header"><h5 class="modal-title">Record Supplier Payment</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Supplier *</label>
                        <select name="supplier_id" class="form-select select2" required>
                            <option value="">Select Supplier</option>
                            <?php foreach ($suppliers as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['supplier_name'] . ($s['company_name'] ? ' (' . $s['company_name'] . ')' : '')) ?> - Bal: <?= formatCurrency($s['current_balance']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount *</label>
                        <input type="number" step="0.01" name="amount" class="form-control" required min="0.01" placeholder="0.00">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Method</label>
                        <select name="payment_method" class="form-select">
                            <option value="Cash">Cash</option>
                            <option value="Card">Card</option>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="Online Payment">Online Payment</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Date</label>
                        <input type="date" name="payment_date" class="form-control" value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2" placeholder="Optional note"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
