<?php
// Redirect to the updated products.php file with wholesale price functionality
// Use relative path from current directory
$redirect_url = 'products.php';

// Check if products.php exists before redirecting
if (file_exists(__DIR__ . '/products.php')) {
    header('Location: ' . $redirect_url);
    exit();
} else {
    // Fallback error message
    die('Error: products.php file not found. Please contact system administrator.');
}
?>

// Handle add category (persistent)
if (isset($_POST['new_category']) && $_POST['new_category'] !== '') {
    $new_category = trim($_POST['new_category']);
    $image_path = null;
    if (isset($_FILES['category_image']) && $_FILES['category_image']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['category_image']['name'], PATHINFO_EXTENSION);
    $image_path = 'uploads/category_' . time() . '_' . rand(1000,9999) . '.' . $ext;
    move_uploaded_file($_FILES['category_image']['tmp_name'], $image_path);
    }
    $stmt = $conn->prepare('INSERT IGNORE INTO categories (name, image) VALUES (?, ?)');
    $stmt->bind_param('ss', $new_category, $image_path);
    if ($stmt->execute()) {
        $message = 'Category added!';
    } else {
        $error = 'Error adding category!';
    }
    $stmt->close();
}

// Handle add/edit product
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'])) {
    $id = $_POST['id'] ?? null;
    $name = $_POST['name'];
    $category = $_POST['category'];
    $price = $_POST['price'];
    $stock = $_POST['stock'];
    $barcode = $_POST['barcode'];
    

    if ($id) {
        // Update existing product
        $stmt = $conn->prepare('UPDATE products SET name = ?, category = ?, price = ?, stock = ?, barcode = ? WHERE id = ?');
        $stmt->bind_param('ssddsi', $name, $category, $price, $stock, $barcode, $id);
        if ($stmt->execute()) {
            $message = 'Product updated successfully!';
        } else {
            $error = 'Error: ' . $stmt->error;
        }
        $stmt->close();
    } else {
        // Add new product
        if (empty($barcode)) {
            $error = 'Please scan the barcode. Each product must have a unique barcode.';
        } else {
            // Check for duplicate barcode
            $stmt_check = $conn->prepare('SELECT id FROM products WHERE barcode = ?');
            $stmt_check->bind_param('s', $barcode);
            $stmt_check->execute();
            $stmt_check->store_result();
            if ($stmt_check->num_rows > 0) {
                $error = 'This barcode already exists. Please scan a unique barcode.';
            } else {
                $stmt = $conn->prepare('INSERT INTO products (name, category, price, stock, barcode) VALUES (?, ?, ?, ?, ?)');
                if ($stmt === false) {
                    $error = 'Prepare failed: ' . $conn->error;
                } else {
                    $stmt->bind_param('ssdds', $name, $category, $price, $stock, $barcode);
                    if ($stmt->execute()) {
                        $new_product_id = $conn->insert_id;
                        
                        // Verify the product was actually inserted
                        $verify = $conn->prepare('SELECT COUNT(*) FROM products WHERE id = ?');
                        $verify->bind_param('i', $new_product_id);
                        $verify->execute();
                        $count = $verify->get_result()->fetch_row()[0];
                        
                        if ($count > 0) {
                            $message = "Product added successfully! (ID: $new_product_id)";
                            
                            // Log the successful addition
                            $log_entry = date('Y-m-d H:i:s') . " - SUCCESS: ID=$new_product_id, Name='$name', Barcode='$barcode', Verified=YES\n";
                            file_put_contents('../product_additions.log', $log_entry, FILE_APPEND | LOCK_EX);
                        } else {
                            $error = "Product insert appeared successful but verification failed!";
                            $log_entry = date('Y-m-d H:i:s') . " - FAILED VERIFICATION: Name='$name', Barcode='$barcode'\n";
                            file_put_contents('../product_additions.log', $log_entry, FILE_APPEND | LOCK_EX);
                        }
                    } else {
                        $error = 'Insert failed: ' . $stmt->error;
                        $log_entry = date('Y-m-d H:i:s') . " - INSERT ERROR: " . $stmt->error . " - Name='$name', Barcode='$barcode'\n";
                        file_put_contents('../product_additions.log', $log_entry, FILE_APPEND | LOCK_EX);
                    }
                }
                $stmt->close();
            }
            $stmt_check->close();
        }
    }
}

// Handle delete (now requires POST to prevent web crawlers)
if (isset($_POST['delete_product'])) {
    $id = $_POST['delete_product'];
    
    // Enhanced security validation
    $csrf_token = $_POST['csrf_token'] ?? '';
    validateDestructiveAction('delete_product', $csrf_token);
    checkHoneypot();
    
    // ENHANCED LOGGING - Track all deletion attempts
    $user_info = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'ANONYMOUS_USER';
    $user_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $referer = $_SERVER['HTTP_REFERER'] ?? 'direct';
    $session_info = isset($_SESSION) ? print_r($_SESSION, true) : 'no_session';
    
    $detailed_log = date('Y-m-d H:i:s') . " - DELETION ATTEMPT INTERCEPTED!\n";
    $detailed_log .= "  Product ID: $id\n";
    $detailed_log .= "  User Session: $user_info\n";
    $detailed_log .= "  IP Address: $user_ip\n";
    $detailed_log .= "  User Agent: $user_agent\n";
    $detailed_log .= "  Referer URL: $referer\n";
    $detailed_log .= "  Full Session Data: $session_info\n";
    $detailed_log .= "  GET Parameters: " . print_r($_GET, true) . "\n";
    $detailed_log .= "  POST Parameters: " . print_r($_POST, true) . "\n";
    $detailed_log .= "  REQUEST METHOD: " . $_SERVER['REQUEST_METHOD'] . "\n";
    $detailed_log .= "  Full URL: " . ($_SERVER['REQUEST_URI'] ?? 'unknown') . "\n\n";
    
    file_put_contents('../deletion_forensics.log', $detailed_log, FILE_APPEND);
    
    // Get product details before deletion for logging
    $product_info = $conn->prepare('SELECT name, barcode FROM products WHERE id = ?');
    $product_info->bind_param('i', $id);
    $product_info->execute();
    $product_data = $product_info->get_result()->fetch_assoc();
    
    $stmt = $conn->prepare('DELETE FROM products WHERE id = ?');
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        $message = 'Product deleted successfully!';
        
        // Log the deletion with details
        $user_info = isset($_SESSION['username']) ? $_SESSION['username'] : 'Unknown';
        $user_ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        $log_entry = date('Y-m-d H:i:s') . " - DELETED: ID=$id, Name='{$product_data['name']}', Barcode='{$product_data['barcode']}', User='$user_info', IP='$user_ip'\n";
        file_put_contents('../product_deletions.log', $log_entry, FILE_APPEND | LOCK_EX);
        
    } else {
        $error = 'Error deleting product!';
    }
    $stmt->close();
}

// Get product for editing
$edit_product = null;
if (isset($_GET['edit'])) {
    $id = $_GET['edit'];
    $stmt = $conn->prepare('SELECT * FROM products WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $edit_product = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

// Fetch all products
$result = $conn->query('SELECT * FROM products ORDER BY name');

// Fetch all categories
$categories_result = $conn->query('SELECT name FROM categories ORDER BY name');
$categories = [];
while ($row = $categories_result->fetch_assoc()) {
    $categories[] = $row['name'];
}

// Handle delete category (now requires POST to prevent web crawlers)
if (isset($_POST['delete_category'])) {
    $cat_id = intval($_POST['delete_category']);
    
    // Enhanced security validation
    $csrf_token = $_POST['csrf_token'] ?? '';
    validateDestructiveAction('delete_category', $csrf_token);
    checkHoneypot();
    $stmt = $conn->prepare('DELETE FROM categories WHERE id = ?');
    $stmt->bind_param('i', $cat_id);
    if ($stmt->execute()) {
        $message = 'Category deleted!';
    } else {
        $error = 'Error deleting category!';
    }
    $stmt->close();
    // Redirect to avoid resubmission
    header('Location: index.php');
    exit;
}

// Fetch all categories with id for management
$categories_manage_result = $conn->query('SELECT id, name, image FROM categories ORDER BY name');
?>
<!DOCTYPE html>
<html>
<head>
    <title>Products - Dilrukshi Tex</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
        .table th, .table td { vertical-align: middle; }
        .low-stock { background-color: #fff3cd !important; }
        .out-of-stock { background-color: #f8d7da !important; }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold"><i class="fas fa-box"></i> Products</h1>
            <div>
                <a href="../pos/" class="btn btn-success me-2"><i class="fas fa-cash-register"></i> POS</a>
                <a href="../" class="btn btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
            </div>
        </div>
        
        <?php if (isset($message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= $error ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <div class="card mb-4">
        <!-- Category Management Panel -->
        <div class="card mb-4">
            <div class="card-header bg-info text-white">
                <i class="fas fa-tags"></i> Manage Categories
            </div>
            <div class="card-body p-0">
                <table class="table table-bordered mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Image</th>
                            <th>Name</th>
                            <th style="width:120px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($cat = $categories_manage_result->fetch_assoc()): ?>
                        <tr>
                            <td>
                                <?php if (!empty($cat['image'])): ?>
                                    <img src="<?= htmlspecialchars($cat['image']) ?>" alt="Category Image" style="width:40px;height:40px;object-fit:cover;border-radius:6px;">
                                <?php else: ?>
                                    <span class="text-muted">No image</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($cat['name']) ?></td>
                            <td>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this category?')">
                                    <input type="hidden" name="delete_category" value="<?= $cat['id'] ?>">
                                    <input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
                                    <?= addHoneypot() ?>
                                    <button type="submit" class="btn btn-sm btn-danger">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <span><i class="fas fa-plus"></i> <?= $edit_product ? 'Edit Product' : 'Add New Product' ?></span>
                <form method="post" enctype="multipart/form-data" class="d-flex align-items-center gap-2">
                    <input type="text" name="new_category" class="form-control form-control-sm" placeholder="Add Category" style="width:140px;">
                    <input type="file" name="category_image" accept="image/*" class="form-control form-control-sm" style="width:180px;">
                    <button type="submit" class="btn btn-light btn-sm">Add</button>
                </form>
            </div>
            <div class="card-body">
                <form method="post" class="row g-3">
                    <?php if ($edit_product): ?>
                    <input type="hidden" name="id" value="<?= $edit_product['id'] ?>">
                    <?php endif; ?>
                    
                    <div class="col-md-3">
                        <label class="form-label">Product Name *</label>
                        <input type="text" name="name" class="form-control" 
                               value="<?= $edit_product['name'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Category</label>
                        <select name="category" class="form-select">
                            <option value="">Select...</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?= htmlspecialchars($cat) ?>" <?= ($edit_product['category'] ?? '') === $cat ? 'selected' : '' ?>><?= htmlspecialchars($cat) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Price *</label>
                        <input type="number" step="0.01" name="price" class="form-control" 
                               value="<?= $edit_product['price'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Stock *</label>
                        <input type="number" name="stock" class="form-control" 
                               value="<?= $edit_product['stock'] ?? '' ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Barcode</label>
                        <input type="text" name="barcode" class="form-control" 
                               value="<?= $edit_product['barcode'] ?? '' ?>">
                    </div>
                    <div class="col-md-1">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save"></i> <?= $edit_product ? 'Update' : 'Add' ?>
                        </button>
                    </div>
                    <?php if ($edit_product): ?>
                    <div class="col-12">
                        <a href="?" class="btn btn-secondary">Cancel Edit</a>
                    </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <span><i class="fas fa-list"></i> Product Inventory</span>
                <small>Total: <?= $result->num_rows ?> products</small>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Category</th>
                                <th>Price</th>
                                <th>Stock</th>
                                <th>Barcode</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $result->fetch_assoc()): ?>
                            <?php 
                            $row_class = '';
                            if ($row['stock'] == 0) $row_class = 'out-of-stock';
                            elseif ($row['stock'] < 10) $row_class = 'low-stock';
                            ?>
                            <tr class="<?= $row_class ?>">
                                <td><?= $row['id'] ?></td>
                                <td>
                                    <strong><?= htmlspecialchars($row['name']) ?></strong>
                                    <?php if ($row['stock'] == 0): ?>
                                    <br><small class="text-danger"><i class="fas fa-exclamation-triangle"></i> Out of Stock</small>
                                    <?php elseif ($row['stock'] < 10): ?>
                                    <br><small class="text-warning"><i class="fas fa-exclamation-triangle"></i> Low Stock</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($row['category']): ?>
                                    <span class="badge bg-secondary"><?= htmlspecialchars($row['category']) ?></span>
                                    <?php endif; ?>
                                </td>
                                <td class="fw-bold text-success">Rs <?= number_format($row['price'], 2) ?></td>
                                <td>
                                    <span class="badge <?= $row['stock'] == 0 ? 'bg-danger' : ($row['stock'] < 10 ? 'bg-warning' : 'bg-success') ?>">
                                        <?= $row['stock'] ?>
                                    </span>
                                </td>
                                <td><code><?= htmlspecialchars($row['barcode'] ?: 'N/A') ?></code></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="?edit=<?= $row['id'] ?>" class="btn btn-outline-primary">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this product?')">
                                            <input type="hidden" name="delete_product" value="<?= $row['id'] ?>">
                                            <input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
                                            <?= addHoneypot() ?>
                                            <button type="submit" class="btn btn-outline-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
