<?php
/**
 * Admin Dashboard
 * Main dashboard page with statistics
 */

$pageTitle = 'Dashboard';

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

$db = Database::getInstance();
$order = new Order();
$product = new Product();
$user = new User();
$cart = new Cart();

// Get statistics
$totalOrders = $db->fetchOne("SELECT COUNT(*) as count FROM orders")['count'] ?? 0;
$totalRevenue = $db->fetchOne("SELECT SUM(total) as total FROM orders WHERE order_status != 'canceled'")['total'] ?? 0;
$totalProducts = $db->fetchOne("SELECT COUNT(*) as count FROM products WHERE is_active = 1")['count'] ?? 0;
$totalCustomers = $db->fetchOne("SELECT COUNT(*) as count FROM users")['count'] ?? 0;

// Today's stats
$todayOrders = $db->fetchOne("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = CURDATE()")['count'] ?? 0;
$todayRevenue = $db->fetchOne("SELECT SUM(total) as total FROM orders WHERE DATE(created_at) = CURDATE() AND order_status != 'canceled'")['total'] ?? 0;

// Pending orders
$pendingOrders = $db->fetchOne("SELECT COUNT(*) as count FROM orders WHERE order_status = 'pending'")['count'] ?? 0;

// Recent orders
$recentOrders = $db->fetchAll(
    "SELECT o.*, u.first_name, u.last_name, u.email 
     FROM orders o 
     LEFT JOIN users u ON o.user_id = u.id 
     ORDER BY o.created_at DESC 
     LIMIT 10"
);

// Abandoned carts
$abandonedCarts = $db->fetchOne(
    "SELECT COUNT(*) as count FROM cart 
     WHERE user_id IS NOT NULL 
     AND updated_at < DATE_SUB(NOW(), INTERVAL 24 HOUR)
     AND id NOT IN (SELECT DISTINCT cart_id FROM orders WHERE cart_id IS NOT NULL)"
)['count'] ?? 0;
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="row g-3 mb-3">
      <div class="col-xxl-6 col-xl-12">
        <div class="card">
          <div class="card-body">
            <div class="row g-0">
              <div class="col-6 col-md-4 border-200 border-bottom border-end pb-4">
                <h6 class="pb-1 text-700">Comenzi</h6>
                <p class="font-sans-serif lh-1 mb-1 fs-7"><?php echo number_format($totalOrders); ?></p>
                <div class="d-flex align-items-center">
                  <h6 class="fs-10 text-500 mb-0">Astăzi: <?php echo $todayOrders; ?></h6>
                </div>
              </div>
              <div class="col-6 col-md-4 border-200 border-bottom border-end-md pb-4 ps-3">
                <h6 class="pb-1 text-700">Venituri</h6>
                <p class="font-sans-serif lh-1 mb-1 fs-7"><?php echo number_format($totalRevenue, 2); ?> RON</p>
                <div class="d-flex align-items-center">
                  <h6 class="fs-10 text-500 mb-0">Astăzi: <?php echo number_format($todayRevenue, 2); ?> RON</h6>
                </div>
              </div>
              <div class="col-6 col-md-4 border-200 border-bottom border-end border-end-md-0 pb-4 pt-4 pt-md-0 ps-md-3">
                <h6 class="pb-1 text-700">Produse</h6>
                <p class="font-sans-serif lh-1 mb-1 fs-7"><?php echo number_format($totalProducts); ?></p>
              </div>
              <div class="col-6 col-md-4 border-200 border-bottom border-bottom-md-0 border-end-md pt-4 pb-md-0 ps-3 ps-md-0">
                <h6 class="pb-1 text-700">Clienți</h6>
                <p class="font-sans-serif lh-1 mb-1 fs-7"><?php echo number_format($totalCustomers); ?></p>
              </div>
              <div class="col-6 col-md-4 border-200 border-bottom-md-0 border-end pt-4 pb-md-0 ps-md-3">
                <h6 class="pb-1 text-700">Comenzi în așteptare</h6>
                <p class="font-sans-serif lh-1 mb-1 fs-7"><?php echo number_format($pendingOrders); ?></p>
              </div>
              <div class="col-6 col-md-4 pb-0 pt-4 ps-3">
                <h6 class="pb-1 text-700">Coșuri abandonate</h6>
                <p class="font-sans-serif lh-1 mb-1 fs-7"><?php echo number_format($abandonedCarts); ?></p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xxl-6 col-xl-12">
        <div class="card">
          <div class="card-header">
            <h6 class="mb-0">Comenzi recente</h6>
          </div>
          <div class="card-body">
            <?php if (empty($recentOrders)): ?>
            <p class="text-600 mb-0">Nu există comenzi recente.</p>
            <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm fs-10 mb-0">
                <thead>
                  <tr>
                    <th>Număr comandă</th>
                    <th>Client</th>
                    <th>Total</th>
                    <th>Status</th>
                    <th>Data</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($recentOrders as $ord): ?>
                  <tr>
                    <td><a href="/admin/comenzi/<?php echo $ord['id']; ?>"><?php echo htmlspecialchars($ord['order_number']); ?></a></td>
                    <td><?php echo htmlspecialchars(($ord['first_name'] ?? '') . ' ' . ($ord['last_name'] ?? '')); ?></td>
                    <td><?php echo number_format($ord['total'], 2); ?> RON</td>
                    <td>
                      <span class="badge badge-subtle-<?php 
                        echo $ord['order_status'] === 'delivered' ? 'success' : 
                            ($ord['order_status'] === 'pending' ? 'warning' : 
                            ($ord['order_status'] === 'canceled' ? 'danger' : 'primary')); 
                      ?>">
                        <?php 
                        $statusText = [
                          'pending' => 'În așteptare',
                          'processing' => 'În procesare',
                          'shipped' => 'Expediată',
                          'delivered' => 'Livrată',
                          'canceled' => 'Anulată'
                        ];
                        echo $statusText[$ord['order_status']] ?? $ord['order_status'];
                        ?>
                      </span>
                    </td>
                    <td><?php echo date('d.m.Y H:i', strtotime($ord['created_at'])); ?></td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

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

