<?php
/**
 * Admin Products Page
 * Product listing and management
 */

$pageTitle = 'Produse';

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../../includes/Product.php';

$db = Database::getInstance();
$product = new Product();

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $productId = intval($_POST['product_id'] ?? 0);
    if ($productId) {
        $db->execute("UPDATE products SET is_active = 0 WHERE id = ?", [$productId]);
        header('Location: /admin/produse?deleted=1');
        exit;
    }
}

// Get products
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$search = $_GET['search'] ?? '';
$categoryId = $_GET['category'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (p.name LIKE ? OR p.sku LIKE ?)";
    $searchTerm = "%{$search}%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($categoryId) {
    $where .= " AND p.category_id = ?";
    $params[] = $categoryId;
}

$products = $db->fetchAll(
    "SELECT p.*, c.name as category_name 
     FROM products p 
     LEFT JOIN categories c ON p.category_id = c.id 
     {$where} 
     ORDER BY p.created_at DESC 
     LIMIT ? OFFSET ?",
    array_merge($params, [$perPage, $offset])
);

$totalProducts = $db->fetchOne(
    "SELECT COUNT(*) as count FROM products p {$where}",
    $params
)['count'] ?? 0;

$totalPages = ceil($totalProducts / $perPage);

// Get categories for filter
$categories = $product->getCategories();
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="card mb-3">
      <div class="card-body">
        <div class="row flex-between-center">
          <div class="col-sm-auto mb-2 mb-sm-0">
            <h6 class="mb-0">Produse: <?php echo number_format($totalProducts); ?></h6>
          </div>
          <div class="col-sm-auto">
            <a class="btn btn-primary btn-sm" href="/admin/produse/adauga">
              <span class="fas fa-plus me-1"></span>Adaugă produs
            </a>
          </div>
        </div>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-body">
        <form method="GET" class="row g-3">
          <div class="col-md-4">
            <input type="text" class="form-control" name="search" placeholder="Caută produs..." value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="col-md-3">
            <select class="form-select" name="category">
              <option value="">Toate categoriile</option>
              <?php foreach ($categories as $cat): ?>
              <option value="<?php echo $cat['id']; ?>" <?php echo ($categoryId == $cat['id']) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($cat['name']); ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">Caută</button>
          </div>
          <div class="col-md-3 text-end">
            <?php if ($search || $categoryId): ?>
            <a href="/admin/produse" class="btn btn-outline-secondary">Resetează</a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>

    <div class="card">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="bg-body-tertiary">
              <tr>
                <th class="text-900 sort" data-sort="name">Produs</th>
                <th class="text-900 sort" data-sort="category">Categorie</th>
                <th class="text-900 sort" data-sort="price">Preț</th>
                <th class="text-900 sort" data-sort="stock">Stoc</th>
                <th class="text-900">Status</th>
                <th class="text-900">Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($products)): ?>
              <tr>
                <td colspan="6" class="text-center py-4">Nu există produse.</td>
              </tr>
              <?php else: ?>
              <?php foreach ($products as $prod): ?>
              <tr>
                <td>
                  <div class="d-flex align-items-center">
                    <img class="me-2" src="<?php echo htmlspecialchars($prod['image'] ?? 'assets/img/shop/electronics/01.png'); ?>" alt="" width="40" height="40" style="object-fit: cover;">
                    <div>
                      <h6 class="mb-0"><?php echo htmlspecialchars($prod['name']); ?></h6>
                      <small class="text-600">SKU: <?php echo htmlspecialchars($prod['sku'] ?? 'N/A'); ?></small>
                    </div>
                  </div>
                </td>
                <td><?php echo htmlspecialchars($prod['category_name'] ?? 'Fără categorie'); ?></td>
                <td>
                  <?php echo number_format($prod['price'], 2); ?> RON
                  <?php if ($prod['sale_price'] && $prod['sale_price'] < $prod['price']): ?>
                  <br><small class="text-danger"><?php echo number_format($prod['sale_price'], 2); ?> RON</small>
                  <?php endif; ?>
                </td>
                <td>
                  <span class="badge badge-subtle-<?php echo $prod['stock_quantity'] > 10 ? 'success' : ($prod['stock_quantity'] > 0 ? 'warning' : 'danger'); ?>">
                    <?php echo number_format($prod['stock_quantity'] ?? 0); ?>
                  </span>
                </td>
                <td>
                  <?php if ($prod['is_active']): ?>
                  <span class="badge badge-subtle-success">Activ</span>
                  <?php else: ?>
                  <span class="badge badge-subtle-danger">Inactiv</span>
                  <?php endif; ?>
                </td>
                <td>
                  <div class="btn-group">
                    <a class="btn btn-sm btn-falcon-default" href="/admin/produse/editeaza/<?php echo htmlspecialchars($prod['slug']); ?>" data-bs-toggle="tooltip" title="Editează">
                      <span class="fas fa-edit"></span>
                    </a>
                    <form method="POST" class="d-inline" onsubmit="return confirm('Ești sigur că vrei să ștergi acest produs?');">
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="product_id" value="<?php echo $prod['id']; ?>">
                      <button type="submit" class="btn btn-sm btn-falcon-default text-danger" data-bs-toggle="tooltip" title="Șterge">
                        <span class="fas fa-trash"></span>
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
      <?php if ($totalPages > 1): ?>
      <div class="card-footer bg-body-tertiary py-2">
        <div class="row flex-between-center">
          <div class="col-auto">
            <small>Pagina <?php echo $page; ?> din <?php echo $totalPages; ?></small>
          </div>
          <div class="col-auto">
            <nav>
              <ul class="pagination pagination-sm mb-0">
                <?php if ($page > 1): ?>
                <li class="page-item">
                  <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId ? '&category=' . $categoryId : ''; ?>">Anterior</a>
                </li>
                <?php endif; ?>
                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                  <a class="page-link" href="?page=<?php echo $i; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId ? '&category=' . $categoryId : ''; ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                <li class="page-item">
                  <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId ? '&category=' . $categoryId : ''; ?>">Următor</a>
                </li>
                <?php endif; ?>
              </ul>
            </nav>
          </div>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

