<?php
session_start();
require_once 'includes/auth.php';
requireLogin();
require_once 'config/database.php';
require_once 'includes/functions.php';

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];

// Handle delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $deleteId = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ? AND company_id = ?");
    $stmt->execute([$deleteId, $companyId]);
    header('Location: products.php?msg=deleted');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM products WHERE company_id = ? ORDER BY type, name");
$stmt->execute([$companyId]);
$products = $stmt->fetchAll();

include 'includes/header.php';
?>

<?php if (isset($_GET['msg'])): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
        <?php 
        if ($_GET['msg'] == 'added') echo 'Product/Service added successfully!';
        if ($_GET['msg'] == 'updated') echo 'Product/Service updated successfully!';
        if ($_GET['msg'] == 'deleted') echo 'Product/Service deleted successfully!';
        ?>
    </div>
<?php endif; ?>

<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
        <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Products & Services</h3>
        <button onclick="openProductModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
            <i class="fas fa-plus mr-2"></i>Add Item
        </button>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-gray-50 dark:bg-gray-700/50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Type</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Name</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">SKU</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Price</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                <?php if (empty($products)): ?>
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center text-gray-500 dark:text-gray-400">No items yet. Click "Add Item" to get started.</td>
                    </tr>
                <?php else: foreach ($products as $product): ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td class="px-6 py-4 text-sm capitalize">
                            <span class="px-2 py-1 text-xs rounded-full <?php echo $product['type'] == 'product' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300' : 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300'; ?>">
                                <?php echo $product['type']; ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white"><?php echo htmlspecialchars($product['name']); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400"><?php echo htmlspecialchars($product['sku'] ?? '-'); ?></td>
                        <td class="px-6 py-4 text-sm font-semibold text-gray-700 dark:text-gray-300"><?php echo formatMoney($product['price'], $company['currency']); ?></td>
                        <td class="px-6 py-4 text-sm">
                            <button onclick="editProduct(<?php echo htmlspecialchars(json_encode($product)); ?>)" class="text-blue-600 hover:text-blue-800 mr-3"><i class="fas fa-edit"></i></button>
                            <a href="?delete=<?php echo $product['id']; ?>" onclick="return confirm('Are you sure? This will affect any invoices using this item.')" class="text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Product Modal -->
<div id="productModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-lg bg-white dark:bg-gray-800">
        <div class="flex justify-between items-center mb-4">
            <h3 id="modalTitle" class="text-lg font-semibold text-gray-800 dark:text-white">Add Product/Service</h3>
            <button onclick="closeProductModal()" class="text-gray-400 hover:text-gray-600">&times;</button>
        </div>
        <form id="productForm" method="POST" action="product-save.php">
            <input type="hidden" name="id" id="productId">
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Type *</label>
                <select name="type" id="productType" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                    <option value="product">Product</option>
                    <option value="service">Service</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Name *</label>
                <input type="text" name="name" id="productName" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            </div>
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Description</label>
                <textarea name="description" id="productDescription" rows="2" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
            </div>
            <div class="grid grid-cols-2 gap-3 mb-3">
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">SKU</label><input type="text" name="sku" id="productSku" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Price *</label><input type="number" step="0.01" name="price" id="productPrice" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
            </div>
            <div class="flex justify-end space-x-3 mt-4">
                <button type="button" onclick="closeProductModal()" class="px-4 py-2 border rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">Cancel</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save</button>
            </div>
        </form>
    </div>
</div>

<script>
function openProductModal() {
    document.getElementById('modalTitle').innerText = 'Add Product/Service';
    document.getElementById('productForm').reset();
    document.getElementById('productId').value = '';
    document.getElementById('productModal').classList.remove('hidden');
}
function closeProductModal() {
    document.getElementById('productModal').classList.add('hidden');
}
function editProduct(product) {
    document.getElementById('modalTitle').innerText = 'Edit Product/Service';
    document.getElementById('productId').value = product.id;
    document.getElementById('productType').value = product.type;
    document.getElementById('productName').value = product.name;
    document.getElementById('productDescription').value = product.description || '';
    document.getElementById('productSku').value = product.sku || '';
    document.getElementById('productPrice').value = product.price;
    document.getElementById('productModal').classList.remove('hidden');
}
</script>

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