<?php
// admin.php - Admin panel with fixed product deletion, always-visible tabs, full editing, image upload, and adjusted margin for sticky header
ob_start();
session_start();
error_log("Entering admin.php: Session ID = " . session_id());

include_once 'config.php';
include_once 'auth.php';
include_once 'functions.php'; // Include for set_flash_message and display_flash_message
include_once 'header.php';

if (!is_admin()) {
    error_log("Non-admin access attempt to admin.php: User ID = " . ($_SESSION['user_id'] ?? 'None'));
    set_flash_message('error', 'Access denied. Admin privileges required.');
    header("Location: index.php");
    ob_end_flush();
    exit();
}

// Generate CSRF token if not set
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    error_log("CSRF token generated: " . $_SESSION['csrf_token']);
}

// Handle product addition
if (isset($_POST['add_product']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $name = sanitize_input($_POST['name']);
    $price = (float)$_POST['price'];
    $description = sanitize_input($_POST['description']);
    $category_id = (int)$_POST['category_id'];
    $stock = (int)$_POST['stock'];
    $is_flash_sale = isset($_POST['is_flash_sale']) ? 1 : 0;
    
    // Handle image upload
    $image = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
        $upload_dir = 'Uploads/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        $image_name = time() . '_' . basename($_FILES['image']['name']);
        $image_path = $upload_dir . $image_name;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $image_path)) {
            $image = $image_path;
        } else {
            error_log("Image upload failed for product: $name");
            set_flash_message('error', 'Image upload failed.');
        }
    }

    $stmt = $conn->prepare("INSERT INTO products (name, price, description, image, category_id, stock, is_flash_sale) VALUES (?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt) {
        error_log("Prepare failed for add_product: " . $conn->error);
        set_flash_message('error', 'Error preparing product addition.');
    } else {
        $stmt->bind_param("sdssiii", $name, $price, $description, $image, $category_id, $stock, $is_flash_sale);
        if ($stmt->execute()) {
            set_flash_message('success', "Product '$name' added successfully.");
            error_log("Product added: $name");
        } else {
            error_log("Error adding product: " . $stmt->error);
            set_flash_message('error', 'Error adding product: ' . htmlspecialchars($stmt->error));
        }
        $stmt->close();
    }
    header("Location: admin.php#products");
    ob_end_flush();
    exit();
}

// Handle product update
if (isset($_POST['update_product']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $id = (int)$_POST['id'];
    $name = sanitize_input($_POST['name']);
    $price = (float)$_POST['price'];
    $description = sanitize_input($_POST['description']);
    $category_id = (int)$_POST['category_id'];
    $stock = (int)$_POST['stock'];
    $is_flash_sale = isset($_POST['is_flash_sale']) ? 1 : 0;
    
    // Handle image upload
    $image = $_POST['existing_image'];
    if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
        $upload_dir = 'Uploads/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        $image_name = time() . '_' . basename($_FILES['image']['name']);
        $image_path = $upload_dir . $image_name;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $image_path)) {
            // Delete old image if it exists and is different
            if ($image && file_exists($image) && $image !== $image_path) {
                unlink($image);
                error_log("Deleted old image: $image");
            }
            $image = $image_path;
        } else {
            error_log("Image upload failed for product update: ID = $id");
            set_flash_message('error', 'Image upload failed.');
        }
    }

    $stmt = $conn->prepare("UPDATE products SET name=?, price=?, description=?, image=?, category_id=?, stock=?, is_flash_sale=? WHERE id=?");
    if (!$stmt) {
        error_log("Prepare failed for update_product: " . $conn->error);
        set_flash_message('error', 'Error preparing product update.');
    } else {
        $stmt->bind_param("sdssiiii", $name, $price, $description, $image, $category_id, $stock, $is_flash_sale, $id);
        if ($stmt->execute()) {
            set_flash_message('success', "Product '$name' updated successfully.");
            error_log("Product updated: ID = $id, Name = $name");
        } else {
            error_log("Error updating product: " . $stmt->error);
            set_flash_message('error', 'Error updating product: ' . htmlspecialchars($stmt->error));
        }
        $stmt->close();
    }
    header("Location: admin.php#products");
    ob_end_flush();
    exit();
}

// Handle product deletion
if (isset($_POST['delete_product']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $id = (int)$_POST['id'];
    error_log("Delete product request: ID = $id, CSRF Token = " . ($_POST['csrf_token'] ?? 'None'));

    // Verify CSRF token explicitly
    if (!$_SESSION['csrf_token'] || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        error_log("CSRF token mismatch: Expected = " . ($_SESSION['csrf_token'] ?? 'None') . ", Received = " . ($_POST['csrf_token'] ?? 'None'));
        set_flash_message('error', 'Invalid CSRF token.');
        header("Location: admin.php#products");
        ob_end_flush();
        exit();
    }

    // Check if product exists
    $stmt = $conn->prepare("SELECT image, name FROM products WHERE id = ?");
    if (!$stmt) {
        error_log("Prepare failed for product deletion validation: " . $conn->error);
        set_flash_message('error', 'Error preparing product deletion: ' . htmlspecialchars($conn->error));
        header("Location: admin.php#products");
        ob_end_flush();
        exit();
    }

    $stmt->bind_param("i", $id);
    if (!$stmt->execute()) {
        error_log("Error validating product: " . $stmt->error);
        set_flash_message('error', 'Error validating product: ' . htmlspecialchars($stmt->error));
        $stmt->close();
        header("Location: admin.php#products");
        ob_end_flush();
        exit();
    }

    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    $stmt->close();

    if (!$product) {
        error_log("Product not found: ID = $id");
        set_flash_message('error', 'Product not found.');
        header("Location: admin.php#products");
        ob_end_flush();
        exit();
    }

    // Delete product from database
    $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
    if (!$stmt) {
        error_log("Prepare failed for product deletion: " . $conn->error);
        set_flash_message('error', 'Error preparing product deletion: ' . htmlspecialchars($conn->error));
        header("Location: admin.php#products");
        ob_end_flush();
        exit();
    }

    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        // Delete associated image file
        if ($product['image'] && file_exists($product['image'])) {
            if (unlink($product['image'])) {
                error_log("Deleted image file: " . $product['image']);
            } else {
                error_log("Failed to delete image file: " . $product['image']);
            }
        }
        set_flash_message('success', "Product '{$product['name']}' (ID #$id) deleted successfully.");
        error_log("Product deleted: ID = $id, Name = " . $product['name']);
    } else {
        error_log("Error deleting product: " . $stmt->error);
        set_flash_message('error', 'Error deleting product: ' . htmlspecialchars($stmt->error));
    }
    $stmt->close();

    header("Location: admin.php#products");
    ob_end_flush();
    exit();
}

// Handle order status update
if (isset($_POST['update_order']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $order_id = (int)$_POST['order_id'];
    $status = sanitize_input($_POST['status']);
    if (!in_array($status, ['pending', 'processing', 'shipped', 'delivered'])) {
        set_flash_message('error', 'Invalid order status.');
        error_log("Invalid order status: $status for Order ID = $order_id");
    } else {
        $stmt = $conn->prepare("UPDATE orders SET status=? WHERE id=?");
        if (!$stmt) {
            error_log("Prepare failed for update_order: " . $conn->error);
            set_flash_message('error', 'Error preparing order update.');
        } else {
            $stmt->bind_param("si", $status, $order_id);
            if ($stmt->execute()) {
                set_flash_message('success', "Order #$order_id status updated to $status.");
                error_log("Order status updated: ID = $order_id, Status = $status");
            } else {
                error_log("Error updating order: " . $stmt->error);
                set_flash_message('error', 'Error updating order: ' . htmlspecialchars($stmt->error));
            }
            $stmt->close();
        }
    }
    header("Location: admin.php#orders");
    ob_end_flush();
    exit();
}

// Fetch products, categories, and orders
try {
    $products = $conn->query("SELECT p.*, c.name as category FROM products p LEFT JOIN categories c ON p.category_id = c.id");
    if (!$products) {
        throw new Exception("Error fetching products: " . $conn->error);
    }
    $categories = $conn->query("SELECT * FROM categories");
    if (!$categories) {
        throw new Exception("Error fetching categories: " . $conn->error);
    }
    $orders = $conn->query("SELECT * FROM orders ORDER BY created_at DESC");
    if (!$orders) {
        throw new Exception("Error fetching orders: " . $conn->error);
    }
} catch (Exception $e) {
    error_log("Fetch error: " . $e->getMessage());
    set_flash_message('error', 'Error fetching data: ' . htmlspecialchars($e->getMessage()));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - Doyle Enterprise</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 { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; }
        .nav-tabs {
            background-color: #f8f9fa; /* Light gray background */
            border-bottom: 3px solid #007BFF; /* Blue border for prominence */
            padding: 15px 0;
            margin-bottom: 25px;
            display: flex; /* Ensure tabs are always visible */
            visibility: visible !important; /* Force visibility */
            opacity: 1 !important; /* Prevent fading */
        }
        .nav-tabs .nav-link {
            color: #6C757D; /* Gray for inactive tabs */
            font-weight: 600; /* Bold text */
            font-size: 1.1rem; /* Larger text for visibility */
            padding: 12px 25px;
            border-radius: 8px 8px 0 0;
            margin-right: 8px;
            border: none;
            background-color: #e9ecef; /* Light gray for inactive tabs */
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        .nav-tabs .nav-link:hover {
            background-color: #d3d6db; /* Slightly darker gray on hover */
            color: #007BFF; /* Blue text on hover */
        }
        .nav-tabs .nav-link.active {
            background-color: #007BFF; /* Deep blue for active tab */
            color: white !important;
            font-weight: 700;
        }
        .table th, .table td {
            vertical-align: middle;
        }
        .btn-primary {
            background-color: #007BFF; /* Blue buttons */
            border-color: #007BFF;
        }
        .btn-primary:hover {
            background-color: #0056b3; /* Darker blue on hover */
        }
        .btn-warning {
            background-color: #FFC107; /* Yellow edit buttons for contrast */
            border-color: #FFC107;
        }
        .btn-danger {
            background-color: #DC3545; /* Red delete buttons */
            border-color: #DC3545;
        }
        .btn-danger:hover {
            background-color: #c82333; /* Darker red on hover */
        }
        .card {
            border: none;
            box-shadow: 0 3px 8px rgba(0,0,0,0.15);
        }
        .modal-content {
            border-radius: 10px;
        }
        .admin-container {
            margin-top: 80px; /* Extra margin to avoid overlap with fixed header */
        }
        .alert {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container admin-container">
        <h2 class="mb-4"><i class="fas fa-cog me-2"></i>Admin Panel</h2>

        <?php display_flash_message(); ?>

        <!-- Always-visible Tabs -->
        <ul class="nav nav-tabs mb-4" id="adminTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="products-tab" data-bs-toggle="tab" data-bs-target="#products" type="button" role="tab" aria-controls="products" aria-selected="true">Products</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="add-product-tab" data-bs-toggle="tab" data-bs-target="#add-product" type="button" role="tab" aria-controls="add-product" aria-selected="false">Add Product</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="orders-tab" data-bs-toggle="tab" data-bs-target="#orders" type="button" role="tab" aria-controls="orders" aria-selected="false">Orders</button>
            </li>
        </ul>

        <div class="tab-content">
            <!-- Products Tab -->
            <div class="tab-pane fade show active" id="products" role="tabpanel" aria-labelledby="products-tab">
                <div class="card p-4">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Price</th>
                                <th>Category</th>
                                <th>Stock</th>
                                <th>Flash Sale</th>
                                <th>Image</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($products->num_rows === 0): ?>
                                <tr><td colspan="8" class="text-center">No products found.</td></tr>
                            <?php else: ?>
                                <?php while ($row = $products->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($row['id']); ?></td>
                                        <td><?php echo htmlspecialchars($row['name']); ?></td>
                                        <td>KSh<?php echo number_format($row['price'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($row['category'] ?? 'Uncategorized'); ?></td>
                                        <td><?php echo htmlspecialchars($row['stock']); ?></td>
                                        <td><?php echo $row['is_flash_sale'] ? '<span class="badge bg-danger">Yes</span>' : 'No'; ?></td>
                                        <td><img src="<?php echo htmlspecialchars($row['image'] ?? 'placeholder.jpg'); ?>" alt="Product" width="50" class="img-fluid"></td>
                                        <td>
                                            <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editProductModal<?php echo $row['id']; ?>">Edit</button>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this product?');">
                                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                                <input type="hidden" name="delete_product" value="1">
                                                <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                    <!-- Edit Product Modal -->
                                    <div class="modal fade" id="editProductModal<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="editProductModalLabel<?php echo $row['id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="editProductModalLabel<?php echo $row['id']; ?>">Edit Product: <?php echo htmlspecialchars($row['name']); ?></h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <form method="post" enctype="multipart/form-data">
                                                        <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                                        <input type="hidden" name="existing_image" value="<?php echo htmlspecialchars($row['image']); ?>">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                                        <div class="mb-3">
                                                            <label class="form-label">Name</label>
                                                            <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($row['name']); ?>">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label">Price</label>
                                                            <input type="number" step="0.01" name="price" class="form-control" required value="<?php echo htmlspecialchars($row['price']); ?>">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label">Description</label>
                                                            <textarea name="description" class="form-control"><?php echo htmlspecialchars($row['description']); ?></textarea>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label">Category</label>
                                                            <select name="category_id" class="form-select">
                                                                <?php
                                                                $cat_result = $conn->query("SELECT * FROM categories");
                                                                while ($cat = $cat_result->fetch_assoc()): ?>
                                                                    <option value="<?php echo $cat['id']; ?>" <?php echo $cat['id'] == $row['category_id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                                                                <?php endwhile; ?>
                                                            </select>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label">Stock</label>
                                                            <input type="number" name="stock" class="form-control" required value="<?php echo htmlspecialchars($row['stock']); ?>">
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label">Flash Sale</label>
                                                            <input type="checkbox" name="is_flash_sale" value="1" <?php echo $row['is_flash_sale'] ? 'checked' : ''; ?>>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label class="form-label">Image</label>
                                                            <input type="file" name="image" class="form-control" accept="image/*">
                                                            <?php if ($row['image']): ?>
                                                                <img src="<?php echo htmlspecialchars($row['image']); ?>" alt="Current Image" class="mt-2 img-fluid" width="100">
                                                            <?php endif; ?>
                                                        </div>
                                                        <button type="submit" name="update_product" class="btn btn-primary">Update Product</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Add Product Tab -->
            <div class="tab-pane fade" id="add-product" role="tabpanel" aria-labelledby="add-product-tab">
                <div class="card p-4">
                    <h4>Add New Product</h4>
                    <form method="post" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                        <div class="mb-3">
                            <label class="form-label">Name</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Price</label>
                            <input type="number" step="0.01" name="price" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Category</label>
                            <select name="category_id" class="form-select">
                                <?php
                                $cat_result = $conn->query("SELECT * FROM categories");
                                while ($cat = $cat_result->fetch_assoc()): ?>
                                    <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Stock</label>
                            <input type="number" name="stock" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Flash Sale</label>
                            <input type="checkbox" name="is_flash_sale" value="1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Image</label>
                            <input type="file" name="image" class="form-control" accept="image/*" required>
                        </div>
                        <button type="submit" name="add_product" class="btn btn-primary">Add Product</button>
                    </form>
                </div>
            </div>

            <!-- Orders Tab -->
            <div class="tab-pane fade" id="orders" role="tabpanel" aria-labelledby="orders-tab">
                <div class="card p-4">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User ID</th>
                                <th>Total</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($orders->num_rows === 0): ?>
                                <tr><td colspan="6" class="text-center">No orders found.</td></tr>
                            <?php else: ?>
                                <?php while ($row = $orders->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($row['id']); ?></td>
                                        <td><?php echo htmlspecialchars($row['user_id']); ?></td>
                                        <td>KES<?php echo number_format($row['total'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($row['status']); ?></td>
                                        <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                                        <td>
                                            <form method="post" class="d-inline">
                                                <input type="hidden" name="order_id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                                <select name="status" class="form-select form-select-sm d-inline w-auto">
                                                    <option value="pending" <?php echo $row['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="processing" <?php echo $row['status'] == 'processing' ? 'selected' : ''; ?>>Processing</option>
                                                    <option value="shipped" <?php echo $row['status'] == 'shipped' ? 'selected' : ''; ?>>Shipped</option>
                                                    <option value="delivered" <?php echo $row['status'] == 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                                                </select>
                                                <button type="submit" name="update_order" class="btn btn-primary btn-sm">Update</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Debug form submission
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', (e) => {
                console.log('Form submitted:', new FormData(form));
            });
        });
    </script>
    <?php include_once 'footer.php'; ?>
</body>
</html>
<?php ob_end_flush(); ?>