<?php
/**
 * Admin Customers Page
 * Customer listing and management
 */

$pageTitle = 'Clienți';

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

$db = Database::getInstance();
$user = new User();

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

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

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

if ($search) {
    $where .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
    $searchTerm = "%{$search}%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$customers = $db->fetchAll(
    "SELECT u.*, 
            (SELECT COUNT(*) FROM orders WHERE user_id = u.id) as total_orders,
            (SELECT SUM(total) FROM orders WHERE user_id = u.id AND order_status != 'canceled') as total_spent
     FROM users u
     {$where}
     ORDER BY u.created_at DESC
     LIMIT ? OFFSET ?",
    array_merge($params, [$perPage, $offset])
);

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

$totalPages = ceil($totalCustomers / $perPage);
?>

<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">Clienți: <?php echo number_format($totalCustomers); ?></h6>
          </div>
        </div>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-body">
        <form method="GET" class="row g-3">
          <div class="col-md-8">
            <input type="text" class="form-control" name="search" placeholder="Caută client (nume, email, telefon)..." value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">Caută</button>
          </div>
          <div class="col-md-2 text-end">
            <?php if ($search): ?>
            <a href="/admin/clienti" 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>Client</th>
                <th>Contact</th>
                <th>Comenzi</th>
                <th>Total cheltuit</th>
                <th>Puncte fidelitate</th>
                <th>Data înregistrare</th>
                <th>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($customers)): ?>
              <tr>
                <td colspan="7" class="text-center py-4">Nu există clienți.</td>
              </tr>
              <?php else: ?>
              <?php foreach ($customers as $customer): ?>
              <tr>
                <td>
                  <div class="d-flex align-items-center">
                    <div class="avatar avatar-s me-2">
                      <div class="avatar-name rounded-circle bg-primary-subtle text-primary">
                        <span><?php echo strtoupper(substr($customer['first_name'], 0, 1) . substr($customer['last_name'], 0, 1)); ?></span>
                      </div>
                    </div>
                    <div>
                      <h6 class="mb-0"><?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?></h6>
                      <?php if ($customer['company_name']): ?>
                      <small class="text-600"><?php echo htmlspecialchars($customer['company_name']); ?></small>
                      <?php endif; ?>
                    </div>
                  </div>
                </td>
                <td>
                  <div><?php echo htmlspecialchars($customer['email']); ?></div>
                  <?php if ($customer['phone']): ?>
                  <small class="text-600"><?php echo htmlspecialchars($customer['phone']); ?></small>
                  <?php endif; ?>
                </td>
                <td><?php echo number_format($customer['total_orders'] ?? 0); ?></td>
                <td><?php echo number_format($customer['total_spent'] ?? 0, 2); ?> RON</td>
                <td>
                  <span class="badge badge-subtle-warning">
                    <?php echo number_format($customer['loyalty_points'] ?? 0); ?> puncte
                  </span>
                </td>
                <td><?php echo date('d.m.Y', strtotime($customer['created_at'])); ?></td>
                <td>
                  <a class="btn btn-sm btn-falcon-default" href="/admin/clienti/<?php echo $customer['id']; ?>" data-bs-toggle="tooltip" title="Detalii">
                    <span class="fas fa-eye"></span>
                  </a>
                </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) : ''; ?>">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 $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) : ''; ?>">Următor</a>
                </li>
                <?php endif; ?>
              </ul>
            </nav>
          </div>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

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

