<?php
/**
 * Studies API
 * Handles study operations (CRUD, status updates)
 */

header('Content-Type: application/json');
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = getCurrentUserId();
$method = $_SERVER['REQUEST_METHOD'];

try {
    $db = getDB();
    
    switch ($method) {
        case 'GET':
            // Get study or list of studies
            if (isset($_GET['id'])) {
                // Get single study
                $studyId = (int)$_GET['id'];
                
                $stmt = $db->prepare("
                    SELECT s.*, u.first_name, u.last_name, c.name as category_name
                    FROM studies s
                    JOIN users u ON s.user_id = u.id
                    LEFT JOIN categories c ON s.category_id = c.id
                    WHERE s.id = ?
                ");
                $stmt->execute([$studyId]);
                $study = $stmt->fetch();
                
                if (!$study) {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Study not found']);
                    exit;
                }
                
                // Check if user has access
                if ($study['status'] !== 'active' && $study['user_id'] !== $userId && !canAccessAdminPanel()) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Access denied']);
                    exit;
                }
                
                // Get collaborators
                $stmt = $db->prepare("
                    SELECT sc.*, u.first_name, u.last_name
                    FROM study_collaborators sc
                    JOIN users u ON sc.user_id = u.id
                    WHERE sc.study_id = ?
                ");
                $stmt->execute([$studyId]);
                $study['collaborators'] = $stmt->fetchAll();
                
                echo json_encode(['success' => true, 'study' => $study]);
                
            } else {
                // Get list of studies
                $status = isset($_GET['status']) ? sanitize($_GET['status']) : null;
                $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
                $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
                
                $sql = "SELECT s.*, u.first_name, u.last_name, c.name as category_name
                        FROM studies s
                        JOIN users u ON s.user_id = u.id
                        LEFT JOIN categories c ON s.category_id = c.id
                        WHERE s.user_id = ?";
                $params = [$userId];
                
                if ($status) {
                    $sql .= " AND s.status = ?";
                    $params[] = $status;
                }
                
                $sql .= " ORDER BY s.created_at DESC LIMIT ? OFFSET ?";
                $params[] = $limit;
                $params[] = $offset;
                
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                $studies = $stmt->fetchAll();
                
                echo json_encode([
                    'success' => true,
                    'studies' => $studies,
                    'total' => count($studies)
                ]);
            }
            break;
            
        case 'POST':
            // Create new study
            $data = json_decode(file_get_contents('php://input'), true);
            
            $required = ['title', 'description', 'type'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || empty($data[$field])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => ucfirst($field) . ' is required']);
                    exit;
                }
            }
            
            $stmt = $db->prepare("
                INSERT INTO studies (user_id, title, description, type, category_id, keywords, status)
                VALUES (?, ?, ?, ?, ?, ?, 'draft')
            ");
            
            $stmt->execute([
                $userId,
                sanitize($data['title']),
                sanitize($data['description']),
                sanitize($data['type']),
                isset($data['category_id']) ? (int)$data['category_id'] : null,
                isset($data['keywords']) ? sanitize($data['keywords']) : null
            ]);
            
            $studyId = $db->lastInsertId();
            
            // Log activity
            logActivity('study_created', 'studies', $studyId);
            
            echo json_encode([
                'success' => true,
                'message' => 'Study created successfully',
                'study_id' => $studyId
            ]);
            break;
            
        case 'PUT':
            // Update study
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Study ID required']);
                exit;
            }
            
            $studyId = (int)$data['id'];
            
            // Verify ownership
            $stmt = $db->prepare("SELECT user_id FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();
            
            if (!$study || ($study['user_id'] !== $userId && !canAccessAdminPanel())) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Build update query
            $updates = [];
            $params = [];
            
            $allowedFields = ['title', 'description', 'type', 'category_id', 'keywords', 'status'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updates[] = "$field = ?";
                    $params[] = $field === 'category_id' ? (int)$data[$field] : sanitize($data[$field]);
                }
            }
            
            if (empty($updates)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'No fields to update']);
                exit;
            }
            
            $params[] = $studyId;
            $sql = "UPDATE studies SET " . implode(', ', $updates) . " WHERE id = ?";
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            
            // Log activity
            logActivity('study_updated', 'studies', $studyId, null, $data);
            
            echo json_encode(['success' => true, 'message' => 'Study updated successfully']);
            break;
            
        case 'DELETE':
            // Delete study
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Study ID required']);
                exit;
            }
            
            $studyId = (int)$data['id'];
            
            // Verify ownership
            $stmt = $db->prepare("SELECT user_id FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();
            
            if (!$study || ($study['user_id'] !== $userId && !canAccessAdminPanel())) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Delete study
            $stmt = $db->prepare("DELETE FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            
            // Log activity
            logActivity('study_deleted', 'studies', $studyId);
            
            echo json_encode(['success' => true, 'message' => 'Study deleted successfully']);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
            break;
    }
    
} catch (Exception $e) {
    error_log("Studies API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
