<?php
session_start();
require_once(__DIR__ . '/../config.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: dashboard.php");
    exit();
}

$success = '';
$error = '';
$name = '';
$description = '';
$price = '';
$stock = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $stock = trim($_POST['stock'] ?? '');

    if ($name === '' || $price === '' || $stock === '') {
        $error = 'Please fill in product name, price, and stock.';
    } elseif (!is_numeric($price) || $price < 0) {
        $error = 'Please enter a valid product price.';
    } elseif (!filter_var($stock, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) && $stock !== '0') {
        $error = 'Please enter a valid stock quantity.';
    } elseif (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Please upload a product image.';
    } else {
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        $extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

        if (!in_array($extension, $allowed_extensions)) {
            $error = 'Image must be JPG, PNG, WEBP, or GIF.';
        } else {
            $image = 'product_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
            $upload_path = __DIR__ . '/../uploads/' . $image;

            if (!move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                $error = 'Could not upload the product image.';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO products (name, description, price, stock, image)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$name, $description, $price, $stock, $image]);

                $success = 'Product added successfully.';
                $name = $description = $price = $stock = '';
            }
        }
    }
}

$stmt = $pdo->query("SELECT * FROM products ORDER BY id DESC LIMIT 6");
$recent_products = $stmt->fetchAll(PDO::FETCH_ASSOC);

include(__DIR__ . '/../header/header.php');
?>

<div class="container-fluid py-4 product-admin-shell">
    <div class="product-admin-hero mb-4">
        <div>
            <p class="text-uppercase text-muted fw-semibold small mb-1">Store management</p>
            <h2 class="fw-bold mb-1">Add Product</h2>
            <p class="text-muted mb-0">Create products that appear on the public products page immediately.</p>
        </div>
        <a href="products.php" class="btn btn-outline-secondary">
            <i class="fas fa-eye me-2"></i>View Store
        </a>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?= htmlspecialchars($success); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i><?= htmlspecialchars($error); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <div class="col-lg-7">
            <div class="product-admin-card">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row g-3">
                        <div class="col-md-7">
                            <label class="form-label fw-semibold">Product name</label>
                            <input name="name" value="<?= htmlspecialchars($name); ?>" placeholder="e.g. Refurbished laptop" class="form-control" required>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label fw-semibold">Price (KES)</label>
                            <input type="number" min="0" step="0.01" name="price" value="<?= htmlspecialchars($price); ?>" placeholder="25000" class="form-control" required>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label fw-semibold">Stock quantity</label>
                            <input type="number" min="0" step="1" name="stock" value="<?= htmlspecialchars($stock); ?>" placeholder="10" class="form-control" required>
                        </div>
                        <div class="col-md-7">
                            <label class="form-label fw-semibold">Product image</label>
                            <input type="file" name="image" class="form-control" accept=".jpg,.jpeg,.png,.webp,.gif" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label fw-semibold">Description</label>
                            <textarea name="description" class="form-control" rows="5" placeholder="Describe product specs, condition, warranty, or service details."><?= htmlspecialchars($description); ?></textarea>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end gap-2 mt-4">
                        <a href="dashboard.php" class="btn btn-outline-secondary">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus-circle me-2"></i>Save Product
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="product-admin-card h-100">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="fw-bold mb-0">Recently Added</h5>
                    <span class="badge bg-warning text-dark"><?= count($recent_products); ?> Items</span>
                </div>

                <?php if (empty($recent_products)): ?>
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-box-open fa-2x mb-3"></i>
                        <p class="mb-0">Products you add will appear here.</p>
                    </div>
                <?php else: ?>
                    <div class="recent-product-list">
                        <?php foreach ($recent_products as $product): ?>
                            <?php
                                $image_src = '../images/lapi.jpg';
                                if (!empty($product['image']) && file_exists(__DIR__ . '/../uploads/' . $product['image'])) {
                                    $image_src = '../uploads/' . $product['image'];
                                }
                            ?>
                            <a href="product_view.php?id=<?= $product['id']; ?>" class="recent-product-item text-decoration-none">
                                <img src="<?= htmlspecialchars($image_src); ?>" alt="<?= htmlspecialchars($product['name']); ?>">
                                <div class="flex-grow-1">
                                    <div class="fw-semibold text-dark"><?= htmlspecialchars($product['name']); ?></div>
                                    <small class="text-muted">KES <?= number_format($product['price']); ?> · Stock <?= (int) $product['stock']; ?></small>
                                </div>
                                <i class="fas fa-chevron-right text-muted"></i>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include(__DIR__ . '/../footer/footer.php'); ?>
