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

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'delete') {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id=?");
        $stmt->execute([(int)$_POST['id']]);
        logActivity('Deleted Product', 'Products', $_POST['id']);
        $_SESSION['success'] = 'Product deleted successfully.';
        header('Location: products.php');
        exit;
    }
    if ($_POST['action'] === 'toggle_status') {
        $id = (int)$_POST['id'];
        $stmt = $pdo->prepare("UPDATE products SET status = CASE WHEN status=1 THEN 0 ELSE 1 END WHERE id=?");
        $stmt->execute([$id]);
        header('Location: products.php');
        exit;
    }
}

$products = $pdo->query("
    SELECT p.*, c.category_name as category_name, b.brand_name as brand_name, s.company_name as supplier_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    LEFT JOIN brands b ON p.brand_id = b.id
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    ORDER BY p.id DESC
")->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-boxes me-2"></i>Products</h4>
            <a href="add_product.php" class="btn btn-primary"><i class="fas fa-plus me-1"></i>Add Product</a>
        </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 class="table table-hover datatable" id="productsTable">
                        <thead>
                            <tr>
                                <th>SKU</th><th>Name</th><th>Type</th><th>Category</th><th>Brand</th>
                                <th>Barcode</th><th>Cost</th><th>Selling</th><th>Stock</th><th>Status</th><th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($products as $p): ?>
                            <tr>
                                <td><?= htmlspecialchars($p['sku']) ?></td>
                                <td><strong><?= htmlspecialchars($p['product_name']) ?></strong><?= $p['model'] ? '<br><small class="text-muted">' . htmlspecialchars($p['model']) . '</small>' : '' ?></td>
                                <td><span class="badge bg-<?= $p['product_type'] == 'Phone' ? 'primary' : ($p['product_type'] == 'Accessory' ? 'success' : 'warning') ?>"><?= $p['product_type'] ?></span></td>
                                <td><?= htmlspecialchars($p['category_name'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($p['brand_name'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($p['barcode'] ?? '-') ?></td>
                                <td><?= formatCurrency($p['cost_price']) ?></td>
                                <td><?= formatCurrency($p['selling_price']) ?></td>
                                <td>
                                    <span class="badge <?= $p['current_stock'] <= $p['low_stock_qty'] ? 'badge-cancelled' : 'badge-completed' ?>"><?= $p['current_stock'] ?></span>
                                </td>
                                <td><?= $p['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td>
                                    <a href="add_product.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-info"><i class="fas fa-edit"></i></a>
                                    <a href="print_barcode.php?product_id=<?= $p['id'] ?>" class="btn btn-sm btn-secondary" target="_blank" title="Print Barcode"><i class="fas fa-barcode"></i></a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this product?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-<?= $p['status'] ? 'warning' : 'success' ?>">
                                            <i class="fas <?= $p['status'] ? 'fa-times' : 'fa-check' ?>"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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