<?php
// Include authentication check
require_once 'auth_check.php';

$pageTitle = 'Products';
$currentPage = 'products';
include 'includes/header.php';
include 'includes/sidebar.php';

// Define path to JSON file and uploads directory
define('JSON_FILE', __DIR__ . '/../database/products.json');
define('UPLOADS_DIR', __DIR__ . '/../assets/uploads/');

// Helper function to read products from JSON
function getProducts() {
    if (!file_exists(JSON_FILE)) {
        return [];
    }
    $json_data = file_get_contents(JSON_FILE);
    return json_decode($json_data, true);
}

// Helper function to save products to JSON
function saveProducts($products) {
    $json_data = json_encode($products, JSON_PRETTY_PRINT);
    file_put_contents(JSON_FILE, $json_data);
}

// Helper function to generate a unique ID
function generateId($products) {
    if (empty($products)) {
        return 1;
    }
    $maxId = max(array_column($products, 'id'));
    return $maxId + 1;
}

// Handle form submissions
$message = '';
$messageType = '';

// Add Product
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $products = getProducts();
    $newId = generateId($products);

    // Handle file upload
    $imagePath = 'https://picsum.photos/250/300?random=' . $newId; // Default placeholder
    if (isset($_FILES['productImage']) && $_FILES['productImage']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['productImage']['tmp_name'];
        $fileName = $_FILES['productImage']['name'];
        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $newFileName = 'product_' . $newId . '.' . $fileExtension;
        $destPath = UPLOADS_DIR . $newFileName;

        if (move_uploaded_file($fileTmpPath, $destPath)) {
            $imagePath = 'assets/uploads/' . $newFileName; // Relative path for web
        }
    }

    $newProduct = [
        'id' => $newId,
        'name' => $_POST['productName'],
        'brand' => $_POST['productBrand'],
        'model' => $_POST['productModel'],
        'price' => (float)$_POST['productPrice'],
        'status' => $_POST['productStatus'],
        'rating' => 'N/A', // Default for new products
        'image' => $imagePath,
        'description' => $_POST['productDescription'] ?? ''
    ];

    $products[] = $newProduct;
    saveProducts($products);
    $message = 'Product added successfully!';
    $messageType = 'success';
    // No redirect, page will reload and show message
}

// Update Product
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $products = getProducts();
    $idToUpdate = (int)$_POST['editProductId'];
    $updated = false;

    foreach ($products as &$product) {
        if ($product['id'] === $idToUpdate) {
            $product['name'] = $_POST['editProductName'];
            $product['brand'] = $_POST['editProductBrand'];
            $product['model'] = $_POST['editProductModel'];
            $product['price'] = (float)$_POST['editProductPrice'];
            $product['status'] = $_POST['editProductStatus'];
            $product['description'] = $_POST['editProductDescription'] ?? '';

            // Handle file upload if a new file is provided
            if (isset($_FILES['editProductImage']) && $_FILES['editProductImage']['error'] === UPLOAD_ERR_OK) {
                $fileTmpPath = $_FILES['editProductImage']['tmp_name'];
                $fileName = $_FILES['editProductImage']['name'];
                $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                $newFileName = 'product_' . $idToUpdate . '.' . $fileExtension;
                $destPath = UPLOADS_DIR . $newFileName;

                if (move_uploaded_file($fileTmpPath, $destPath)) {
                    $product['image'] = 'assets/uploads/' . $newFileName; // Relative path for web
                }
            }
            $updated = true;
            break;
        }
    }

    if ($updated) {
        saveProducts($products);
        $message = 'Product updated successfully!';
        $messageType = 'success';
    } else {
        $message = 'Product not found.';
        $messageType = 'danger';
    }
    // No redirect, page will reload and show message
}

// Delete Product (changed to POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $products = getProducts();
    $idToDelete = (int)$_POST['deleteProductId'];
    $products = array_filter($products, function($product) use ($idToDelete) {
        return $product['id'] !== $idToDelete;
    });
    // Re-index array after filtering
    $products = array_values($products);
    saveProducts($products);
    $message = 'Product deleted successfully!';
    $messageType = 'success';
    // No redirect, page will reload and show message
}

$products = getProducts();
?>
        <div class="page-header">
            <div>
                <h1>Products Management</h1>
                <p class="lead">View and manage all your products.</p>
            </div>
            <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#addProductModal">
                <i class="fas fa-plus mr-1"></i> Add New Product
            </a>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>

        <div class="products-table-container">
            <h2>All Products</h2>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th scope="col" style="width: 50px;">ID</th>
                            <th scope="col" style="width: 80px;">Image</th>
                            <th scope="col">Name</th>
                            <th scope="col" style="width: 120px;">Brand</th>
                            <th scope="col" style="width: 150px;">Model</th>
                            <th scope="col" style="width: 110px;">Price</th>
                            <th scope="col" style="width: 130px;">Stock Status</th>
                            <th scope="col" style="width: 80px;">Rating</th>
                            <th scope="col" style="width: 150px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($products)): ?>
                            <tr>
                                <td colspan="9" class="text-center">No products found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($products as $product): ?>
                                <?php
                                    // Fix image path for display
                                    $productImage = $product['image'] ?? 'https://via.placeholder.com/80x80.png?text=No+Image';
                                    // Fix image path if it starts with '../'
                                    if (strpos($productImage, '../') === 0) {
                                        $productImage = '../' . $productImage;
                                    } elseif (strpos($productImage, 'assets/') === 0) {
                                        $productImage = '../' . $productImage;
                                    }
                                ?>
                                <tr>
                                    <th scope="row"><?php echo $product['id']; ?></th>
                                    <td><img src="<?php echo htmlspecialchars($productImage); ?>" alt="Product Image" class="product-image-thumbnail"></td>
                                    <td class="product-name-cell" title="<?php echo htmlspecialchars($product['name']); ?>"><?php echo htmlspecialchars($product['name']); ?></td>
                                    <td><?php echo htmlspecialchars($product['brand']); ?></td>
                                    <td><?php echo htmlspecialchars($product['model']); ?></td>
                                    <td><?php echo number_format($product['price'], 2, ',', '.'); ?> RON</td>
                                    <td><span class="badge badge-<?php echo strtolower(str_replace(' ', '-', $product['status'])); ?>"><?php echo htmlspecialchars($product['status']); ?></span></td>
                                    <td><?php echo htmlspecialchars($product['rating']); ?></td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-primary" data-toggle="modal" data-target="#viewProductModal" data-id="<?php echo $product['id']; ?>" data-name="<?php echo htmlspecialchars($product['name']); ?>" data-price="<?php echo $product['price']; ?>" data-brand="<?php echo htmlspecialchars($product['brand']); ?>" data-model="<?php echo htmlspecialchars($product['model']); ?>" data-status="<?php echo htmlspecialchars($product['status']); ?>" data-image="<?php echo htmlspecialchars($productImage); ?>" title="View">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-warning" data-toggle="modal" data-target="#editProductModal" data-id="<?php echo $product['id']; ?>" data-name="<?php echo htmlspecialchars($product['name']); ?>" data-price="<?php echo $product['price']; ?>" data-brand="<?php echo htmlspecialchars($product['brand']); ?>" data-model="<?php echo htmlspecialchars($product['model']); ?>" data-status="<?php echo htmlspecialchars($product['status']); ?>" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-danger btn-action" data-toggle="modal" data-target="#deleteProductModal" data-id="<?php echo $product['id']; ?>" data-name="<?php echo htmlspecialchars($product['name']); ?>">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <!-- Pagination (can be implemented later) -->
        </div>
    </main>
</div>
</div>

<!-- Add Product Modal -->
<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addProductModalLabel">Add New Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addProductForm" action="products.php" method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="add">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="productName">Product Name</label>
                            <input type="text" class="form-control" id="productName" name="productName" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="productBrand">Brand</label>
                            <input type="text" class="form-control" id="productBrand" name="productBrand" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="productModel">Model</label>
                            <input type="text" class="form-control" id="productModel" name="productModel" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="productPrice">Price</label>
                            <input type="number" class="form-control" id="productPrice" name="productPrice" step="0.01" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="productDescription">Description</label>
                        <textarea class="form-control" id="productDescription" name="productDescription" rows="3"></textarea>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="productStatus">Stock Status</label>
                            <select class="form-control" id="productStatus" name="productStatus">
                                <option value="In Stock">In Stock</option>
                                <option value="Limited Stock">Limited Stock</option>
                                <option value="Preorder">Preorder</option>
                                <option value="Out of Stock">Out of Stock</option>
                                <option value="Catalog">Catalog</option>
                            </select>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="productImage">Product Image</label>
                            <input type="file" class="form-control-file" id="productImage" name="productImage" accept="image/*">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="submit" form="addProductForm" class="btn btn-primary">Save Product</button>
            </div>
        </div>
    </div>
</div>

<!-- View Product Modal -->
<div class="modal fade" id="viewProductModal" tabindex="-1" aria-labelledby="viewProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewProductModalLabel">Product Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-4">
                        <img id="modalProductImage" src="" alt="Product Image" class="img-fluid rounded">
                    </div>
                    <div class="col-md-8">
                        <p><strong>ID:</strong> <span id="modalProductId"></span></p>
                        <p><strong>Name:</strong> <span id="modalProductName"></span></p>
                        <p><strong>Brand:</strong> <span id="modalProductBrand"></span></p>
                        <p><strong>Model:</strong> <span id="modalProductModel"></span></p>
                        <p><strong>Price:</strong> <span id="modalProductPrice"></span></p>
                        <p><strong>Status:</strong> <span id="modalProductStatus"></span></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Product Modal -->
<div class="modal fade" id="editProductModal" tabindex="-1" aria-labelledby="editProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editProductModalLabel">Edit Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editProductForm" action="products.php" method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" id="editProductId" name="editProductId">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="editProductName">Product Name</label>
                            <input type="text" class="form-control" id="editProductName" name="editProductName" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="editProductBrand">Brand</label>
                            <input type="text" class="form-control" id="editProductBrand" name="editProductBrand" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="editProductModel">Model</label>
                            <input type="text" class="form-control" id="editProductModel" name="editProductModel" required>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="editProductPrice">Price</label>
                            <input type="number" class="form-control" id="editProductPrice" name="editProductPrice" step="0.01" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="editProductDescription">Description</label>
                        <textarea class="form-control" id="editProductDescription" name="editProductDescription" rows="3"></textarea>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="editProductStatus">Stock Status</label>
                            <select class="form-control" id="editProductStatus" name="editProductStatus">
                                <option value="In Stock">In Stock</option>
                                <option value="Limited Stock">Limited Stock</option>
                                <option value="Preorder">Preorder</option>
                                <option value="Out of Stock">Out of Stock</option>
                                <option value="Catalog">Catalog</option>
                            </select>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="editProductImage">Change Product Image (Optional)</label>
                            <input type="file" class="form-control-file" id="editProductImage" name="editProductImage" accept="image/*">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="submit" form="editProductForm" class="btn btn-primary">Update Product</button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Product Modal -->
<div class="modal fade" id="deleteProductModal" tabindex="-1" aria-labelledby="deleteProductModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteProductModalLabel">Delete Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete product <strong id="deleteProductName"></strong>? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <!-- Form for POST request -->
                <form id="deleteProductForm" action="products.php" method="post" style="display: inline;">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" id="deleteProductIdInput" name="deleteProductId" value="">
                    <button type="submit" class="btn btn-danger">Delete Product</button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
.product-image-thumbnail {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #ddd;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.product-name-cell {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

#modalProductImage {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
</style>

<script>
// Handle view product modal
$('#viewProductModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var id = button.data('id');
    var name = button.data('name');
    var price = button.data('price');
    var brand = button.data('brand');
    var model = button.data('model');
    var status = button.data('status');
    var image = button.data('image');
    
    var modal = $(this);
    modal.find('#modalProductId').text(id);
    modal.find('#modalProductName').text(name);
    modal.find('#modalProductBrand').text(brand);
    modal.find('#modalProductModel').text(model);
    modal.find('#modalProductPrice').text(price.toLocaleString('ro-RO', {minimumFractionDigits: 2}) + ' RON');
    modal.find('#modalProductStatus').text(status);
    modal.find('#modalProductImage').attr('src', image);
});

// Handle delete product modal
$('#deleteProductModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var id = button.data('id');
    var name = button.data('name');
    
    var modal = $(this);
    modal.find('#deleteProductName').text(name);
    modal.find('#deleteProductIdInput').val(id);
});

// Handle edit product modal
$('#editProductModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var id = button.data('id');
    var name = button.data('name');
    var price = button.data('price');
    var brand = button.data('brand');
    var model = button.data('model');
    var status = button.data('status');
    
    var modal = $(this);
    modal.find('#editProductId').val(id);
    modal.find('#editProductName').val(name);
    modal.find('#editProductBrand').val(brand);
    modal.find('#editProductModel').val(model);
    modal.find('#editProductPrice').val(price);
    modal.find('#editProductStatus').val(status);
});
</script>

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