<?php
/**
 * ============================================================================
 * ajax/bookmark-content.php - Bookmark Learning Content
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if (!isset($_POST['content_type']) || !isset($_POST['content_id'])) {
    echo json_encode(['success' => false, 'message' => 'Content type and ID required']);
    exit;
}

$userId = getUserId();
$content_type = $_POST['content_type'];
$content_id = intval($_POST['content_id']);

// Validate content type
$valid_types = ['tip', 'disease', 'schedule', 'variety', 'video', 'resource'];
if (!in_array($content_type, $valid_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid content type']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if already bookmarked
    $check_sql = "SELECT id, status FROM learning_progress 
                  WHERE user_id = ? AND content_type = ? AND content_id = ?";
    $check_stmt = $db->prepare($check_sql);
    $check_stmt->execute([$userId, $content_type, $content_id]);
    $existing = $check_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing) {
        // Toggle bookmark
        if ($existing['status'] == 'bookmarked') {
            $sql = "UPDATE learning_progress 
                    SET status = 'viewed', updated_at = NOW() 
                    WHERE id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$existing['id']]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Bookmark removed',
                'bookmarked' => false
            ]);
        } else {
            $sql = "UPDATE learning_progress 
                    SET status = 'bookmarked', updated_at = NOW() 
                    WHERE id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$existing['id']]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Content bookmarked',
                'bookmarked' => true
            ]);
        }
    } else {
        // Create new bookmark
        $sql = "INSERT INTO learning_progress (user_id, content_type, content_id, status) 
                VALUES (?, ?, ?, 'bookmarked')";
        $stmt = $db->prepare($sql);
        $stmt->execute([$userId, $content_type, $content_id]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Content bookmarked',
            'bookmarked' => true
        ]);
    }
    
} catch (PDOException $e) {
    error_log("Database error in bookmark-content.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to bookmark content'
    ]);
}
?>