<?php
session_start();
require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Handle actions (Approve/Reject)
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $action = db_prepare($con, $_GET['action']);
    $status = '';
    $msg = '';

    // Fetch product name for logging
    $q = mysqli_query($con, "SELECT productName FROM products WHERE id='$id'");
    $r = mysqli_fetch_assoc($q);
    $prod_name = $r['productName'] ?? 'Unknown';

    if ($action == 'approve') {
        $status = 'approved';
        $msg = "Product approved successfully!";
        log_activity("Approved Product", "Name: $prod_name, ID: $id");
    } elseif ($action == 'reject') {
        $status = 'rejected';
        $msg = "Product rejected.";
        log_activity("Rejected Product", "Name: $prod_name, ID: $id");
    }

    if ($status) {
        mysqli_query($con, "UPDATE products SET approval_status='$status' WHERE id='$id'");
        $_SESSION['msg'] = $msg;
        header('location: pending-products.php');
        exit;
    }
}

// Get pending products
$pendingQuery = mysqli_query($con, "SELECT p.*, v.store_name, c.categoryName, s.subcategory 
                                    FROM products p 
                                    LEFT JOIN vendors v ON p.vendor_id = v.id
                                    LEFT JOIN category c ON p.category = c.id
                                    LEFT JOIN subcategory s ON p.subCategory = s.id
                                    WHERE p.approval_status='pending' 
                                    GROUP BY p.id
                                    ORDER BY p.postingDate DESC");

$productsData = [];
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Pending Products - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-clock me-2"></i> Pending Product Approvals</h1>
                            <p>Review vendor product submissions</p>
                        </div>
                    </div>

                    <!-- Messages -->
                    <?php if (isset($_SESSION['msg'])): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Pending Products Table -->
                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>Products Awaiting Approval</h5>
                        </div>
                        <div class="card-body">
                            <?php if (mysqli_num_rows($pendingQuery) > 0): ?>
                                <table class="table table-hover" id="datatablesSimple">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Image</th>
                                            <th>Product</th>
                                            <th>Vendor</th>
                                            <th>Category</th>
                                            <th>Price</th>
                                            <th>Stock</th>
                                            <th>Submitted</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $cnt = 1;
                                        while ($product = mysqli_fetch_assoc($pendingQuery)) {
                                            // Store data for JS
                                            $productsData[$product['id']] = [
                                                'id' => $product['id'],
                                                'name' => htmlentities($product['productName']),
                                                'sku' => htmlentities($product['sku'] ?? 'N/A'),
                                                'vendor' => htmlentities($product['store_name']),
                                                'category' => htmlentities($product['categoryName']),
                                                'subcategory' => htmlentities($product['subcategory']),
                                                'brand' => htmlentities($product['productCompany'] ?? 'N/A'),
                                                'price' => number_format($product['productPrice'], 2),
                                                'stock' => $product['stock_quantity'],
                                                'desc' => nl2br(htmlentities($product['productDescription'])),
                                                'img1' => $product['productImage1'],
                                                'img2' => $product['productImage2'],
                                                'img3' => $product['productImage3'],
                                                'avail' => $product['productAvailability']
                                            ];
                                            ?>
                                            <tr>
                                                <td><?php echo $cnt; ?></td>
                                                <td>
                                                    <?php if ($product['productImage1']): ?>
                                                        <img src="productimages/<?php echo $product['id']; ?>/<?php echo $product['productImage1']; ?>"
                                                            class="rounded" style="width: 50px; height: 50px; object-fit: cover;">
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <strong><?php echo htmlentities($product['productName']); ?></strong>
                                                    <?php if ($product['sku']): ?>
                                                        <br><small class="text-muted">SKU:
                                                            <?php echo htmlentities($product['sku']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo htmlentities($product['store_name']); ?></td>
                                                <td><?php echo htmlentities($product['categoryName']); ?></td>
                                                <td><strong>₵ <?php echo number_format($product['productPrice'], 2); ?></strong>
                                                </td>
                                                <td><?php echo $product['stock_quantity']; ?></td>
                                                <td><?php echo date('M d, Y', strtotime($product['postingDate'])); ?></td>
                                                <td>
                                                    <button class="btn btn-sm btn-info"
                                                        onclick="viewProduct(<?php echo $product['id']; ?>)">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <a href="?action=approve&id=<?php echo $product['id']; ?>"
                                                        class="btn btn-sm btn-success"
                                                        onclick="return confirm('Approve this product?');">
                                                        <i class="fas fa-check"></i>
                                                    </a>
                                                    <a href="?action=reject&id=<?php echo $product['id']; ?>"
                                                        class="btn btn-sm btn-danger"
                                                        onclick="return confirm('Reject this product?');">
                                                        <i class="fas fa-times"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php $cnt++;
                                        } ?>
                                    </tbody>
                                </table>
                            <?php else: ?>
                                <div class="alert alert-success text-center">
                                    <i class="fas fa-check-circle fa-3x mb-3"></i>
                                    <h5>All Caught Up!</h5>
                                    <p class="mb-0">No pending product approvals at this time.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <!-- Single View Modal -->
    <div class="modal fade" id="productModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Product Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4" id="modalImages">
                            <!-- Images loaded via JS -->
                        </div>
                        <div class="col-md-8">
                            <h5 id="modalName"></h5>
                            <table class="table table-bordered mt-3">
                                <tr>
                                    <th width="35%">Vendor</th>
                                    <td id="modalVendor"></td>
                                </tr>
                                <tr>
                                    <th>Category</th>
                                    <td id="modalCategory"></td>
                                </tr>
                                <tr>
                                    <th>Brand</th>
                                    <td id="modalBrand"></td>
                                </tr>
                                <tr>
                                    <th>SKU</th>
                                    <td id="modalSku"></td>
                                </tr>
                                <tr>
                                    <th>Price</th>
                                    <td><strong>₵ <span id="modalPrice"></span></strong></td>
                                </tr>
                                <tr>
                                    <th>Stock</th>
                                    <td id="modalStock"></td>
                                </tr>
                                <tr>
                                    <th>Availability</th>
                                    <td id="modalAvail"></td>
                                </tr>
                            </table>
                            <h6>Description:</h6>
                            <div class="p-2 bg-light rounded" id="modalDesc"></div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <a href="#" id="btnReject" class="btn btn-danger"><i class="fas fa-times me-2"></i>Reject</a>
                    <a href="#" id="btnApprove" class="btn btn-success"><i class="fas fa-check me-2"></i>Approve</a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest"></script>
    <script src="js/datatables-simple-demo.js"></script>

    <script>
        const products = <?php echo json_encode($productsData); ?>;
        const productModal = new bootstrap.Modal(document.getElementById('productModal'));

        function viewProduct(id) {
            const p = products[id];
            if (!p) return;

            // Populate Text
            document.getElementById('modalName').textContent = p.name;
            document.getElementById('modalVendor').textContent = p.vendor;
            document.getElementById('modalCategory').textContent = p.category + ' > ' + p.subcategory;
            document.getElementById('modalBrand').textContent = p.brand;
            document.getElementById('modalSku').textContent = p.sku;
            document.getElementById('modalPrice').textContent = p.price;
            document.getElementById('modalStock').textContent = p.stock;
            document.getElementById('modalAvail').textContent = p.avail;
            document.getElementById('modalDesc').innerHTML = p.desc;

            // Populate Images
            let imgsHtml = '';
            if (p.img1) imgsHtml += `<img src="productimages/${id}/${p.img1}" class="img-fluid rounded mb-2">`;
            if (p.img2) imgsHtml += `<img src="productimages/${id}/${p.img2}" class="img-fluid rounded mb-2">`;
            if (p.img3) imgsHtml += `<img src="productimages/${id}/${p.img3}" class="img-fluid rounded">`;
            document.getElementById('modalImages').innerHTML = imgsHtml;

            // Update Action Buttons
            document.getElementById('btnApprove').href = `?action=approve&id=${id}`;
            document.getElementById('btnReject').href = `?action=reject&id=${id}`;

            productModal.show();
        }
    </script>
</body>

</html>