<?php
// ============================================================
// backend/api/admin/AdminController.php
// ============================================================

class AdminController {

    private PDO $db;

    public function __construct() {
        $this->db = getDB();
        requireAdmin(); // all admin routes are protected
    }

    // ======================== STATS ========================

    public function stats(): void {
        $totals = [];
        foreach (['users','classes','products','orders','events'] as $table) {
            $totals[$table] = (int) $this->db->query("SELECT COUNT(*) FROM $table")->fetchColumn();
        }
        $revenue = $this->db->query("SELECT COALESCE(SUM(total),0) FROM orders WHERE status = 'paid'")->fetchColumn();
        $totals['revenue'] = (float) $revenue;

        $recentOrders = $this->db->query(
            "SELECT o.id, u.name, o.total, o.status, o.created_at
             FROM orders o JOIN users u ON u.id = o.user_id
             ORDER BY o.created_at DESC LIMIT 5"
        )->fetchAll();

        sendSuccess(['totals' => $totals, 'recent_orders' => $recentOrders]);
    }

    // ======================== CLASSES ========================

    public function getClasses(): void {
        $rows = $this->db->query(
            'SELECT c.*, (SELECT COUNT(*) FROM enrollments e WHERE e.class_id = c.id) AS enrolled FROM classes c ORDER BY c.class_date DESC'
        )->fetchAll();
        sendSuccess($rows);
    }

    public function createClass(): void {
        $b = $GLOBALS['body'];
        $this->validateClassBody($b);
        $stmt = $this->db->prepare(
            'INSERT INTO classes (title, description, instructor, price, class_date, duration_min, meeting_link, image, seats)
             VALUES (?,?,?,?,?,?,?,?,?)'
        );
        $stmt->execute([
            $b['title'], $b['description'], $b['instructor'],
            $b['price'], $b['class_date'], $b['duration_min'] ?? 60,
            $b['meeting_link'] ?? null, $b['image'] ?? null, $b['seats'] ?? 50,
        ]);
        sendSuccess(['id' => (int)$this->db->lastInsertId()], 'Class created', 201);
    }

    public function updateClass(?string $id): void {
        if (!$id) sendError('Class ID required', 422);
        $b = $GLOBALS['body'];
        $stmt = $this->db->prepare(
            'UPDATE classes SET title=?, description=?, instructor=?, price=?, class_date=?,
             duration_min=?, meeting_link=?, image=?, seats=?, status=? WHERE id=?'
        );
        $stmt->execute([
            $b['title'], $b['description'], $b['instructor'],
            $b['price'], $b['class_date'], $b['duration_min'] ?? 60,
            $b['meeting_link'] ?? null, $b['image'] ?? null,
            $b['seats'] ?? 50, $b['status'] ?? 'active', $id,
        ]);
        sendSuccess([], 'Class updated');
    }

    public function deleteClass(?string $id): void {
        if (!$id) sendError('Class ID required', 422);
        $this->db->prepare('DELETE FROM classes WHERE id = ?')->execute([$id]);
        sendSuccess([], 'Class deleted');
    }

    // ======================== PRODUCTS ========================

    public function getProducts(): void {
        sendSuccess($this->db->query('SELECT * FROM products ORDER BY created_at DESC')->fetchAll());
    }

    public function createProduct(): void {
        $b = $GLOBALS['body'];
        if (empty($b['name']) || empty($b['price'])) sendError('Name and price required', 422);
        $stmt = $this->db->prepare(
            'INSERT INTO products (name, description, price, stock, image, category, featured)
             VALUES (?,?,?,?,?,?,?)'
        );
        $stmt->execute([
            $b['name'], $b['description'] ?? '', $b['price'],
            $b['stock'] ?? 0, $b['image'] ?? null,
            $b['category'] ?? null, (int)($b['featured'] ?? 0),
        ]);
        sendSuccess(['id' => (int)$this->db->lastInsertId()], 'Product created', 201);
    }

    public function updateProduct(?string $id): void {
        if (!$id) sendError('Product ID required', 422);
        $b = $GLOBALS['body'];
        $stmt = $this->db->prepare(
            'UPDATE products SET name=?, description=?, price=?, stock=?, image=?, category=?, featured=? WHERE id=?'
        );
        $stmt->execute([
            $b['name'], $b['description'] ?? '', $b['price'],
            $b['stock'] ?? 0, $b['image'] ?? null,
            $b['category'] ?? null, (int)($b['featured'] ?? 0), $id,
        ]);
        sendSuccess([], 'Product updated');
    }

    public function deleteProduct(?string $id): void {
        if (!$id) sendError('Product ID required', 422);
        $this->db->prepare('DELETE FROM products WHERE id = ?')->execute([$id]);
        sendSuccess([], 'Product deleted');
    }

    // ======================== EVENTS ========================

    public function getEvents(): void {
        sendSuccess($this->db->query('SELECT * FROM events ORDER BY event_date DESC')->fetchAll());
    }

    public function createEvent(): void {
        $b = $GLOBALS['body'];
        if (empty($b['title']) || empty($b['event_date'])) sendError('Title and event_date required', 422);
        $stmt = $this->db->prepare(
            'INSERT INTO events (title, description, event_date, location, image, status) VALUES (?,?,?,?,?,?)'
        );
        $stmt->execute([
            $b['title'], $b['description'] ?? '',
            $b['event_date'], $b['location'] ?? null,
            $b['image'] ?? null, $b['status'] ?? 'upcoming',
        ]);
        sendSuccess(['id' => (int)$this->db->lastInsertId()], 'Event created', 201);
    }

    public function updateEvent(?string $id): void {
        if (!$id) sendError('Event ID required', 422);
        $b = $GLOBALS['body'];
        $stmt = $this->db->prepare(
            'UPDATE events SET title=?, description=?, event_date=?, location=?, image=?, status=? WHERE id=?'
        );
        $stmt->execute([
            $b['title'], $b['description'] ?? '',
            $b['event_date'], $b['location'] ?? null,
            $b['image'] ?? null, $b['status'] ?? 'upcoming', $id,
        ]);
        sendSuccess([], 'Event updated');
    }

    public function deleteEvent(?string $id): void {
        if (!$id) sendError('Event ID required', 422);
        $this->db->prepare('DELETE FROM events WHERE id = ?')->execute([$id]);
        sendSuccess([], 'Event deleted');
    }

    // ======================== ORDERS ========================

    public function getOrders(): void {
        $rows = $this->db->query(
            'SELECT o.*, u.name AS customer_name, u.email AS customer_email
             FROM orders o JOIN users u ON u.id = o.user_id
             ORDER BY o.created_at DESC'
        )->fetchAll();
        sendSuccess($rows);
    }

    public function updateOrderStatus(?string $id): void {
        if (!$id) sendError('Order ID required', 422);
        $status = $GLOBALS['body']['status'] ?? '';
        $allowed = ['pending','paid','shipped','delivered','cancelled'];
        if (!in_array($status, $allowed)) sendError("Invalid status. Use: " . implode(', ', $allowed), 422);
        $this->db->prepare('UPDATE orders SET status = ? WHERE id = ?')->execute([$status, $id]);
        sendSuccess([], 'Order status updated');
    }

    // ======================== USERS ========================

    public function getUsers(): void {
        $rows = $this->db->query(
            'SELECT id, name, email, role, created_at FROM users ORDER BY created_at DESC'
        )->fetchAll();
        sendSuccess($rows);
    }

    // ======================== HELPERS ========================

    private function validateClassBody(array $b): void {
        $required = ['title', 'description', 'instructor', 'price', 'class_date'];
        $errors = [];
        foreach ($required as $field) {
            if (empty($b[$field])) $errors[$field] = "$field is required";
        }
        if ($errors) sendError('Validation failed', 422, $errors);
    }
}
