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

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $supplier_name = trim($_POST['supplier_name']);
        $contact_person = trim($_POST['contact_person']);
        $phone = trim($_POST['phone']);
        $email = trim($_POST['email']);
        $address = trim($_POST['address']);
        $company_name = trim($_POST['company_name']);
        $balance = (float)($_POST['opening_balance'] ?? 0);
        $status = isset($_POST['status']) ? 1 : 0;

        if (empty($supplier_name) || empty($phone)) {
            $_SESSION['error'] = 'Supplier name and phone are required.';
        } else {
            try {
                if ($action === 'add') {
                    $code = generateSupplierCode();
                    $stmt = $pdo->prepare("INSERT INTO suppliers (supplier_code, supplier_name, contact_person, phone, email, address, company_name, opening_balance, current_balance, status) VALUES (?,?,?,?,?,?,?,?,?,?)");
                    $stmt->execute([$code, $supplier_name, $contact_person, $phone, $email, $address, $company_name, $balance, $balance, $status]);
                    logActivity('Created Supplier', 'Suppliers', $pdo->lastInsertId(), "Supplier: $supplier_name");
                    $_SESSION['success'] = 'Supplier added successfully.';
                } else {
                    $stmt = $pdo->prepare("UPDATE suppliers SET supplier_name=?, contact_person=?, phone=?, email=?, address=?, company_name=?, opening_balance=?, status=? WHERE id=?");
                    $stmt->execute([$supplier_name, $contact_person, $phone, $email, $address, $company_name, $balance, $status, $id]);
                    logActivity('Updated Supplier', 'Suppliers', $id, "Supplier: $supplier_name");
                    $_SESSION['success'] = 'Supplier updated successfully.';
                }
            } catch (PDOException $e) { $_SESSION['error'] = 'Error: ' . $e->getMessage(); }
        }
        header('Location: suppliers.php'); exit;
    }
    if ($action === 'delete') {
        $id = (int)$_POST['id'];
        $check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE supplier_id=?");
        $check->execute([$id]);
        $c1 = $check->fetchColumn();
        $check = $pdo->prepare("SELECT COUNT(*) FROM purchases WHERE supplier_id=?");
        $check->execute([$id]);
        $c2 = $check->fetchColumn();
        if ($c1 + $c2 > 0) {
            $_SESSION['error'] = 'Cannot delete: supplier has ' . ($c1 ? "$c1 product(s)" : '') . ($c1 && $c2 ? ' and ' : '') . ($c2 ? "$c2 purchase(s)" : '') . '.';
        } else {
            $stmt = $pdo->prepare("DELETE FROM suppliers WHERE id=?");
            $stmt->execute([$id]);
            $_SESSION['success'] = 'Supplier deleted successfully.';
        }
        header('Location: suppliers.php'); exit;
    }
}

$suppliers = $pdo->query("SELECT s.*, (SELECT COUNT(*) FROM products WHERE supplier_id=s.id) as product_count, (SELECT COUNT(*) FROM purchases WHERE supplier_id=s.id) as purchase_count FROM suppliers s ORDER BY s.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-truck me-2"></i>Suppliers</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#supplierModal" onclick="resetSupplierForm()"><i class="fas fa-plus me-1"></i>Add Supplier</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="suppliersTable" class="table table-hover datatable">
                        <thead><tr><th>Code</th><th>Name</th><th>Contact</th><th>Phone</th><th>Balance</th><th>Products</th><th>Purchases</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($suppliers as $s): ?>
                            <tr>
                                <td><code><?= htmlspecialchars($s['supplier_code']) ?></code></td>
                                <td><strong><?= htmlspecialchars($s['supplier_name']) ?></strong><?= $s['company_name'] ? '<br><small class="text-muted">' . htmlspecialchars($s['company_name']) . '</small>' : '' ?></td>
                                <td><?= htmlspecialchars($s['contact_person'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($s['phone']) ?></td>
                                <td><?= formatCurrency($s['current_balance']) ?></td>
                                <td><span class="badge bg-secondary"><?= (int)$s['product_count'] ?></span></td>
                                <td><span class="badge bg-secondary"><?= (int)$s['purchase_count'] ?></span></td>
                                <td><?= $s['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td>
                                    <a href="view_supplier.php?id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-info"><i class="fas fa-eye"></i></a>
                                    <button class="btn btn-sm btn-info" onclick="editSupplier(<?= htmlspecialchars(json_encode($s)) ?>)"><i class="fas fa-edit"></i></button>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete supplier <?= htmlspecialchars($s['supplier_name']) ?>?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Supplier Modal -->
<div class="modal fade" id="supplierModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" id="supAction" value="add">
                <input type="hidden" name="id" id="supId" value="0">
                <div class="modal-header"><h5 class="modal-title" id="supModalTitle">Add Supplier</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Supplier Name *</label>
                            <input type="text" name="supplier_name" id="supName" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Company Name</label>
                            <input type="text" name="company_name" id="supCompany" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Contact Person</label>
                            <input type="text" name="contact_person" id="supPerson" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Phone *</label>
                            <input type="text" name="phone" id="supPhone" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" id="supEmail" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Opening Balance</label>
                            <input type="number" step="0.01" name="opening_balance" id="supBalance" class="form-control" value="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Address</label>
                        <textarea name="address" id="supAddress" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" name="status" id="supStatus" class="form-check-input" checked>
                        <label class="form-check-label">Active</label>
                    </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">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetSupplierForm() {
    $('#supAction').val('add');
    $('#supId').val(0);
    $('#supModalTitle').text('Add Supplier');
    $('#supName').val('');
    $('#supCompany').val('');
    $('#supPerson').val('');
    $('#supPhone').val('');
    $('#supEmail').val('');
    $('#supAddress').val('');
    $('#supBalance').val('0');
    $('#supStatus').prop('checked', true);
}
function editSupplier(s) {
    $('#supAction').val('edit');
    $('#supId').val(s.id);
    $('#supModalTitle').text('Edit Supplier: ' + s.supplier_name);
    $('#supName').val(s.supplier_name);
    $('#supCompany').val(s.company_name || '');
    $('#supPerson').val(s.contact_person || '');
    $('#supPhone').val(s.phone);
    $('#supEmail').val(s.email || '');
    $('#supAddress').val(s.address || '');
    $('#supBalance').val(s.opening_balance);
    $('#supStatus').prop('checked', s.status == 1);
    $('#supplierModal').modal('show');
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
