<?php
// Cart API for managing course enrollment cart
// Handles adding/removing courses, calculating totals, and checkout logic

require_once '../includes/middleware.php';
require_once '../config/database.php';
require_once '../config/currency.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];

class CartManager {
    private $db;
    private $userId;

    public function __construct($db, $userId = null) {
        $this->db = $db;
        $this->userId = $userId;
    }

    public function getCart() {
        if (!$this->userId) {
            return ['items' => [], 'total' => 0.00, 'currency' => 'USD'];
        }

        // Get cart items from database (courses and exams)
        $stmt = $this->db->prepare("
            SELECT ci.*,
                   COALESCE(c.title, e.title) as title,
                   COALESCE(c.price, e.price) as price,
                   COALESCE(c.currency, e.currency) as currency,
                   COALESCE(c.is_free, e.is_free) as is_free,
                   COALESCE(c.thumbnail, NULL) as thumbnail,
                   COALESCE(c.max_students, NULL) as max_students,
                   ci.item_type
            FROM cart_items ci
            LEFT JOIN courses c ON ci.item_id = c.id AND ci.item_type = 'course'
            LEFT JOIN exams e ON ci.item_id = e.id AND ci.item_type = 'exam'
            WHERE ci.user_id = ?
            ORDER BY ci.created_at ASC
        ");
        $stmt->execute([$this->userId]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $total = 0.00;
        $currency = 'USD';

        foreach ($items as &$item) {
            if (!$item['is_free']) {
                $total += floatval($item['price']);
                $currency = $item['currency'];
            }
        }

        return [
            'items' => $items,
            'total' => $total,
            'currency' => $currency,
            'item_count' => count($items)
        ];
    }

    public function addToCart($itemId, $itemType = 'course') {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required'];
        }

        $table = $itemType === 'exam' ? 'exams' : 'courses';
        $statusField = $itemType === 'exam' ? 'status' : 'status';
        $statusValue = 'published';

        // Check if item exists and is published
        $stmt = $this->db->prepare("SELECT id, title, is_free FROM {$table} WHERE id = ? AND {$statusField} = ?");
        $stmt->execute([$itemId, $statusValue]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$item) {
            return ['success' => false, 'error' => ucfirst($itemType) . ' not found'];
        }

        // Check if already enrolled/purchased
        if ($itemType === 'course') {
            $stmt = $this->db->prepare("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status != 'dropped'");
            $stmt->execute([$itemId, $this->userId]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Already enrolled in this course'];
            }
        } else {
            // For exams, check if already attempted
            $stmt = $this->db->prepare("SELECT id FROM exam_attempts WHERE exam_id = ? AND student_id = ?");
            $stmt->execute([$itemId, $this->userId]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Already attempted this exam'];
            }
        }

        // Check if already in cart
        $stmt = $this->db->prepare("SELECT id FROM cart_items WHERE user_id = ? AND item_id = ? AND item_type = ?");
        $stmt->execute([$this->userId, $itemId, $itemType]);
        $existingCartItem = $stmt->fetch();

        if ($existingCartItem) {
            // Item already in cart - update timestamp to indicate recent activity
            $stmt = $this->db->prepare("UPDATE cart_items SET updated_at = NOW() WHERE id = ?");
            $stmt->execute([$existingCartItem['id']]);
            return ['success' => true, 'message' => ucfirst($itemType) . ' already in cart', 'already_in_cart' => true];
        }

        // Add to cart
        $stmt = $this->db->prepare("INSERT INTO cart_items (user_id, item_type, item_id, created_at) VALUES (?, ?, ?, NOW())");
        $stmt->execute([$this->userId, $itemType, $itemId]);

        return ['success' => true, 'message' => ucfirst($itemType) . ' added to cart'];
    }

    public function removeFromCart($itemId, $itemType = 'course') {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required'];
        }

        $stmt = $this->db->prepare("DELETE FROM cart_items WHERE user_id = ? AND item_id = ? AND item_type = ?");
        $stmt->execute([$this->userId, $itemId, $itemType]);

        return ['success' => true, 'message' => ucfirst($itemType) . ' removed from cart'];
    }

    public function clearCart() {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required'];
        }

        $stmt = $this->db->prepare("DELETE FROM cart_items WHERE user_id = ?");
        $stmt->execute([$this->userId]);

        return ['success' => true, 'message' => 'Cart cleared'];
    }

    public function checkout() {
        if (!$this->userId) {
            return ['success' => false, 'error' => 'Authentication required', 'auth_required' => true];
        }

        $cart = $this->getCart();

        if (empty($cart['items'])) {
            return ['success' => false, 'error' => 'Cart is empty'];
        }

        // Separate free and paid items
        $freeItems = [];
        $paidItems = [];

        foreach ($cart['items'] as $item) {
            if ($item['is_free']) {
                $freeItems[] = $item;
            } else {
                $paidItems[] = $item;
            }
        }

        // If cart total is $0.00 (all free items), enroll/purchase directly
        if ($cart['total'] == 0.00) {
            return $this->processFreeItems($freeItems);
        }

        // If cart has paid items, return payment details
        return [
            'success' => true,
            'payment_required' => true,
            'cart' => $cart,
            'free_items' => $freeItems,
            'paid_items' => $paidItems
        ];
    }

    private function processFreeItems($freeItems) {
        $processedItems = [];
        $errors = [];

        foreach ($freeItems as $item) {
            try {
                if ($item['item_type'] === 'course') {
                    // Check enrollment limits for courses
                    if ($item['max_students'] > 0) {
                        $stmt = $this->db->prepare("SELECT COUNT(*) FROM course_enrollments WHERE course_id = ? AND status != 'dropped'");
                        $stmt->execute([$item['item_id']]);
                        $enrollmentCount = $stmt->fetchColumn();

                        if ($enrollmentCount >= $item['max_students']) {
                            $errors[] = "Course '{$item['title']}' is full";
                            continue;
                        }
                    }

                    // Create course enrollment
                    $stmt = $this->db->prepare("INSERT INTO course_enrollments (course_id, student_id, payment_status, payment_amount, status, enrollment_date, created_at) VALUES (?, ?, 'paid', 0.00, 'active', NOW(), NOW())");
                    $stmt->execute([$item['item_id'], $this->userId]);

                    // Log activity
                    if (function_exists('logUserActivity')) {
                        logUserActivity($this->userId, 'course_enrollment', "Enrolled in course ID: {$item['item_id']}");
                    }
                } else {
                    // For exams, create exam_access record
                    $stmt = $this->db->prepare("
                        INSERT INTO exam_access (exam_id, student_id, payment_status, payment_amount, access_granted_at)
                        VALUES (?, ?, 'paid', 0.00, NOW())
                        ON DUPLICATE KEY UPDATE access_granted_at = NOW()
                    ");
                    $stmt->execute([$item['item_id'], $this->userId]);

                    // Log activity
                    if (function_exists('logUserActivity')) {
                        logUserActivity($this->userId, 'exam_access', "Gained access to exam ID: {$item['item_id']}");
                    }
                }

                $processedItems[] = $item['title'];

            } catch (Exception $e) {
                $errors[] = "Failed to process '{$item['title']}': " . $e->getMessage();
            }
        }

        // Clear cart after successful processing
        if (!empty($processedItems)) {
            $this->clearCart();
        }

        return [
            'success' => true,
            'enrolled_items' => $processedItems,
            'errors' => $errors,
            'message' => count($processedItems) . ' item(s) processed successfully'
        ];
    }
}

try {
    $userId = $_SESSION['user_id'] ?? null;

    // Handle session cart for non-logged in users
    if (!$userId) {
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }
    }

    $cartManager = $userId ? new CartManager($db, $userId) : null;

    switch ($method) {
        case 'GET':
            // Get cart contents
            if (!$userId) {
                $cartItems = [];
                if (!empty($_SESSION['cart'])) {
                    $placeholders = str_repeat('?,', count($_SESSION['cart']) - 1) . '?';
                    $stmt = $db->prepare("SELECT id, title, price, currency, is_free, thumbnail FROM courses WHERE id IN ($placeholders) AND status = 'published'");
                    $stmt->execute($_SESSION['cart']);
                    $courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    foreach ($courses as $course) {
                        $cartItems[] = [
                            'item_id' => $course['id'],
                            'title' => $course['title'],
                            'price' => $course['price'],
                            'currency' => $course['currency'],
                            'is_free' => $course['is_free'],
                            'thumbnail' => $course['thumbnail']
                        ];
                    }
                }

                $total = 0.00;
                $currency = 'USD';
                foreach ($cartItems as $item) {
                    if (!$item['is_free']) {
                        $total += floatval($item['price']);
                        $currency = $item['currency'];
                    }
                }

                $cart = ['items' => $cartItems, 'total' => $total, 'currency' => $currency, 'item_count' => count($cartItems)];
                echo json_encode(['success' => true, 'cart' => $cart]);
            } else {
                $cart = $cartManager->getCart();
                echo json_encode(['success' => true, 'cart' => $cart]);
            }
            break;

        case 'POST':
            // Add item to cart
            $data = json_decode(file_get_contents('php://input'), true);
            $itemId = $data['item_id'] ?? $data['course_id'] ?? null; // Support both item_id and course_id for backward compatibility
            $itemType = $data['item_type'] ?? 'course';

            if (!$itemId) {
                echo json_encode(['success' => false, 'error' => ucfirst($itemType) . ' ID required']);
                exit;
            }

            if (!$userId) {
                // Handle session cart for non-logged in users (only courses for now)
                if ($itemType !== 'course') {
                    echo json_encode(['success' => false, 'error' => 'Please login to add exams to cart']);
                    exit;
                }

                if (!isset($_SESSION['cart'])) {
                    $_SESSION['cart'] = [];
                }

                // Check if course exists and is published
                $stmt = $db->prepare("SELECT id, title FROM courses WHERE id = ? AND status = 'published'");
                $stmt->execute([$itemId]);
                $course = $stmt->fetch(PDO::FETCH_ASSOC);

                if (!$course) {
                    echo json_encode(['success' => false, 'error' => 'Course not found']);
                    exit;
                }

                // Check if already in session cart
                if (in_array($itemId, $_SESSION['cart'])) {
                    echo json_encode(['success' => true, 'message' => 'Course already in cart', 'already_in_cart' => true]);
                } else {
                    $_SESSION['cart'][] = $itemId;
                    echo json_encode(['success' => true, 'message' => 'Course added to cart']);
                }
            } else {
                $result = $cartManager->addToCart($itemId, $itemType);
                echo json_encode($result);
            }
            break;

        case 'DELETE':
            // Remove item from cart or clear cart
            $itemId = $_GET['item_id'] ?? $_GET['course_id'] ?? null; // Support both for backward compatibility
            $itemType = $_GET['item_type'] ?? 'course';

            if (!$userId) {
                // Handle session cart for non-logged in users (only courses)
                if ($itemType !== 'course') {
                    echo json_encode(['success' => false, 'error' => 'Please login to manage exam cart']);
                    exit;
                }

                if ($itemId) {
                    // Remove specific course from session cart
                    if (isset($_SESSION['cart'])) {
                        $_SESSION['cart'] = array_filter($_SESSION['cart'], function($id) use ($itemId) {
                            return $id != $itemId;
                        });
                        echo json_encode(['success' => true, 'message' => 'Course removed from cart']);
                    } else {
                        echo json_encode(['success' => false, 'error' => 'Cart is empty']);
                    }
                } else {
                    // Clear session cart
                    $_SESSION['cart'] = [];
                    echo json_encode(['success' => true, 'message' => 'Cart cleared']);
                }
            } else {
                if ($itemId) {
                    $result = $cartManager->removeFromCart($itemId, $itemType);
                } else {
                    $result = $cartManager->clearCart();
                }
                echo json_encode($result);
            }
            break;

        case 'PUT':
            // Checkout
            $result = $cartManager->checkout();
            echo json_encode($result);
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            break;
    }

} catch (Exception $e) {
    error_log("Cart API Error: " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Server error: ' . $e->getMessage()]);
}
?>