<?php
/**
 * Admin Orders Page
 * Order listing and management
 */

$pageTitle = 'Comenzi';

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

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

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $orderId = intval($_POST['order_id'] ?? 0);
    $newStatus = $_POST['status'] ?? '';
    if ($orderId && $newStatus) {
        $db->execute(
            "UPDATE orders SET order_status = ?, updated_at = NOW() WHERE id = ?",
            [$newStatus, $orderId]
        );
        header('Location: /admin/comenzi?updated=1');
        exit;
    }
}

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

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

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

if ($status) {
    $where .= " AND o.order_status = ?";
    $params[] = $status;
}

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

$orders = $db->fetchAll(
    "SELECT o.*, u.first_name, u.last_name, u.email, u.phone
     FROM orders o
     LEFT JOIN users u ON o.user_id = u.id
     {$where}
     ORDER BY o.created_at DESC
     LIMIT ? OFFSET ?",
    array_merge($params, [$perPage, $offset])
);

$totalOrders = $db->fetchOne(
    "SELECT COUNT(*) as count FROM orders o LEFT JOIN users u ON o.user_id = u.id {$where}",
    $params
)['count'] ?? 0;

$totalPages = ceil($totalOrders / $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">Comenzi: <?php echo number_format($totalOrders); ?></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-4">
            <input type="text" class="form-control" name="search" placeholder="Caută comandă sau client..." value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="col-md-3">
            <select class="form-select" name="status">
              <option value="">Toate statusurile</option>
              <option value="pending" <?php echo ($status === 'pending') ? 'selected' : ''; ?>>În așteptare</option>
              <option value="processing" <?php echo ($status === 'processing') ? 'selected' : ''; ?>>În procesare</option>
              <option value="shipped" <?php echo ($status === 'shipped') ? 'selected' : ''; ?>>Expediată</option>
              <option value="delivered" <?php echo ($status === 'delivered') ? 'selected' : ''; ?>>Livrată</option>
              <option value="canceled" <?php echo ($status === 'canceled') ? 'selected' : ''; ?>>Anulată</option>
            </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 || $status): ?>
            <a href="/admin/comenzi" 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>Număr comandă</th>
                <th>Client</th>
                <th>Total</th>
                <th>Status</th>
                <th>Data</th>
                <th>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($orders)): ?>
              <tr>
                <td colspan="6" class="text-center py-4">Nu există comenzi.</td>
              </tr>
              <?php else: ?>
              <?php foreach ($orders as $ord): ?>
              <tr>
                <td>
                  <a href="/admin/comenzi/<?php echo $ord['id']; ?>" class="fw-bold">
                    <?php echo htmlspecialchars($ord['order_number']); ?>
                  </a>
                </td>
                <td>
                  <?php if ($ord['first_name']): ?>
                  <div><?php echo htmlspecialchars($ord['first_name'] . ' ' . $ord['last_name']); ?></div>
                  <small class="text-600"><?php echo htmlspecialchars($ord['email']); ?></small>
                  <?php else: ?>
                  <span class="text-600">Client anonim</span>
                  <?php endif; ?>
                </td>
                <td><?php echo number_format($ord['total'], 2); ?> RON</td>
                <td>
                  <form method="POST" class="d-inline">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="order_id" value="<?php echo $ord['id']; ?>">
                    <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
                      <option value="pending" <?php echo ($ord['order_status'] === 'pending') ? 'selected' : ''; ?>>În așteptare</option>
                      <option value="processing" <?php echo ($ord['order_status'] === 'processing') ? 'selected' : ''; ?>>În procesare</option>
                      <option value="shipped" <?php echo ($ord['order_status'] === 'shipped') ? 'selected' : ''; ?>>Expediată</option>
                      <option value="delivered" <?php echo ($ord['order_status'] === 'delivered') ? 'selected' : ''; ?>>Livrată</option>
                      <option value="canceled" <?php echo ($ord['order_status'] === 'canceled') ? 'selected' : ''; ?>>Anulată</option>
                    </select>
                  </form>
                </td>
                <td><?php echo date('d.m.Y H:i', strtotime($ord['created_at'])); ?></td>
                <td>
                  <a class="btn btn-sm btn-falcon-default" href="/admin/comenzi/<?php echo $ord['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 $status ? '&status=' . urlencode($status) : ''; ?><?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 $status ? '&status=' . urlencode($status) : ''; ?><?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 $status ? '&status=' . urlencode($status) : ''; ?><?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'; ?>

