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

$vendorId = $_SESSION['vendor_id'];

// Handle delete
if (isset($_GET['del'])) {
    $productId = intval($_GET['del']);

    // Verify product belongs to this vendor
    $checkOwner = mysqli_query($con, "SELECT id FROM products WHERE id='$productId' AND vendor_id='$vendorId'");
    if (mysqli_num_rows($checkOwner) > 0) {
        // Delete product images directory from disk
        $dirPath = "../../__admin__/productimages/" . $productId;
        if (is_dir($dirPath)) {
            $files = glob($dirPath . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            rmdir($dirPath);
        }

        mysqli_query($con, "DELETE FROM products WHERE id='$productId'");
        $_SESSION['msg'] = "Product deleted successfully!";
    } else {
        $_SESSION['error'] = "Unauthorized action!";
    }
    header('location:manage-products.php');
    exit;
}

// Get vendor's products
$productsQuery = mysqli_query($con, "SELECT p.*, c.categoryName, s.subcategory 
                                     FROM products p 
                                     LEFT JOIN category c ON p.category = c.id 
                                     LEFT JOIN subcategory s ON p.subCategory = s.id 
                                     WHERE p.vendor_id='$vendorId' 
                                     ORDER BY p.postingDate DESC");
?>

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

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Manage Products - Vendor Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="../../__admin__/css/styles.css" rel="stylesheet" />
    <link href="../../__admin__/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-boxes me-2"></i> Manage Products</h1>
                            <p>View and manage your product listings</p>
                        </div>
                        <div>
                            <a href="add-product.php" class="btn btn-primary">
                                <i class="fas fa-plus me-2"></i>Add New Product
                            </a>
                        </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 } ?>

                    <?php if (isset($_SESSION['error'])) { ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <!-- Products Table -->
                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>Your Products</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-hover" id="datatablesSimple">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="10%">Image</th>
                                        <th>Product Name</th>
                                        <th>Category</th>
                                        <th>Price</th>
                                        <th>Stock</th>
                                        <th>Status</th>
                                        <th>Approval</th>
                                        <th width="12%">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $cnt = 1;
                                    while ($row = mysqli_fetch_array($productsQuery)) {
                                        $statusClass = $row['productAvailability'] == 'In Stock' ? 'success' : 'danger';
                                        $approvalClass = 'warning';
                                        if ($row['approval_status'] == 'approved')
                                            $approvalClass = 'success';
                                        elseif ($row['approval_status'] == 'rejected')
                                            $approvalClass = 'danger';
                                        ?>
                                        <tr>
                                            <td>
                                                <?php echo $cnt; ?>
                                            </td>
                                            <td>
                                                <?php if ($row['productImage1']): ?>
                                                    <img src="../../__admin__/productimages/<?php echo $row['id']; ?>/<?php echo $row['productImage1']; ?>"
                                                        alt="Product"
                                                        style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">
                                                <?php else: ?>
                                                    <div
                                                        style="width: 50px; height: 50px; background: #f0f0f0; border-radius: 4px;">
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <strong>
                                                    <?php echo htmlentities($row['productName']); ?>
                                                </strong>
                                                <?php if ($row['sku']): ?>
                                                    <br><small class="text-muted">SKU:
                                                        <?php echo htmlentities($row['sku']); ?>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo htmlentities($row['categoryName']); ?>
                                            </td>
                                            <td><strong>₵
                                                    <?php echo number_format($row['productPrice'], 2); ?>
                                                </strong></td>
                                            <td>
                                                <?php echo $row['stock_quantity']; ?>
                                                <?php if ($row['stock_quantity'] < 10): ?>
                                                    <i class="fas fa-exclamation-triangle text-warning" title="Low stock"></i>
                                                <?php endif; ?>
                                            </td>
                                            <td><span class="badge bg-<?php echo $statusClass; ?>">
                                                    <?php echo $row['productAvailability']; ?>
                                                </span></td>
                                            <td><span class="badge bg-<?php echo $approvalClass; ?>">
                                                    <?php echo ucfirst($row['approval_status']); ?>
                                                </span></td>
                                            <td>
                                                <a href="edit-product.php?id=<?php echo $row['id']; ?>"
                                                    class="btn btn-sm btn-outline-primary" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?del=<?php echo $row['id']; ?>"
                                                    class="btn btn-sm btn-outline-danger"
                                                    onclick="return confirm('Delete this product?');" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php
                                        $cnt++;
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('../includes/footer.php'); ?>
        </div>
    </div>

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

</html>