<?php
require_once 'config.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

$action = $_GET['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

// Helper function to send JSON response
function sendResponse($status, $message, $data = null) {
    $response = ['status' => $status, 'message' => $message];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit();
}

// Test endpoint to check if API is working
if ($action === 'test') {
    sendResponse('success', 'XAMPP integration active', ['timestamp' => date('Y-m-d H:i:s')]);
}

// Require login for most endpoints
if (!in_array($action, ['test', 'login'])) {
    if (!isLoggedIn()) {
        sendResponse('error', 'Authentication required');
    }
}

switch($action) {
    case 'login':
        if ($method !== 'POST') {
            sendResponse('error', 'Method not allowed');
        }
        
        $username = sanitizeInput($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $role = sanitizeInput($_POST['role'] ?? '');
        
        if (empty($username) || empty($password) || empty($role)) {
            sendResponse('error', 'All fields are required');
        }
        
        try {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = MD5(?) AND role = ? AND status = 'aktif'");
            $stmt->execute([$username, $password, $role]);
            $user = $stmt->fetch();
            
            if ($user) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['name'] = $user['name'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['class'] = $user['class'];
                $_SESSION['subject'] = $user['subject'];
                
                sendResponse('success', 'Login successful', [
                    'user' => [
                        'id' => $user['id'],
                        'name' => $user['name'],
                        'role' => $user['role'],
                        'class' => $user['class'],
                        'subject' => $user['subject']
                    ]
                ]);
            } else {
                sendResponse('error', 'Invalid credentials');
            }
        } catch(PDOException $e) {
            sendResponse('error', 'Database error');
        }
        break;
        
    case 'get_tasks':
        try {
            if ($_SESSION['role'] === 'siswa') {
                $stmt = $pdo->prepare("SELECT * FROM tasks WHERE student_id = ? ORDER BY submit_date DESC");
                $stmt->execute([$_SESSION['user_id']]);
            } elseif ($_SESSION['role'] === 'guru') {
                $stmt = $pdo->prepare("
                    SELECT t.*, u.name as student_name, u.class as student_class 
                    FROM tasks t 
                    JOIN users u ON t.student_id = u.id 
                    WHERE t.subject = ? 
                    ORDER BY t.submit_date DESC
                ");
                $stmt->execute([$_SESSION['subject']]);
            } else {
                $stmt = $pdo->prepare("
                    SELECT t.*, u.name as student_name, u.class as student_class 
                    FROM tasks t 
                    JOIN users u ON t.student_id = u.id 
                    ORDER BY t.submit_date DESC
                ");
                $stmt->execute();
            }
            
            $tasks = $stmt->fetchAll();
            sendResponse('success', 'Tasks retrieved successfully', $tasks);
        } catch(PDOException $e) {
            sendResponse('error', 'Database error');
        }
        break;
        
    case 'get_users':
        if ($_SESSION['role'] !== 'admin') {
            sendResponse('error', 'Access denied');
        }
        
        try {
            $type = $_GET['type'] ?? 'all';
            
            if ($type === 'students') {
                $stmt = $pdo->prepare("SELECT id, name, username, class, nis, status, created_at FROM users WHERE role = 'siswa' ORDER BY name");
            } elseif ($type === 'teachers') {
                $stmt = $pdo->prepare("SELECT id, name, username, subject, nip, status, created_at FROM users WHERE role = 'guru' ORDER BY name");
            } else {
                $stmt = $pdo->prepare("SELECT id, name, username, role, class, subject, status, created_at FROM users WHERE role != 'admin' ORDER BY role, name");
            }
            
            $stmt->execute();
            $users = $stmt->fetchAll();
            sendResponse('success', 'Users retrieved successfully', $users);
        } catch(PDOException $e) {
            sendResponse('error', 'Database error');
        }
        break;
        
    case 'update_grade':
        if ($_SESSION['role'] !== 'guru') {
            sendResponse('error', 'Access denied');
        }
        
        if ($method !== 'POST') {
            sendResponse('error', 'Method not allowed');
        }
        
        $task_id = intval($_POST['task_id'] ?? 0);
        $grade = intval($_POST['grade'] ?? 0);
        $feedback = sanitizeInput($_POST['feedback'] ?? '');
        
        if ($task_id <= 0 || $grade < 0 || $grade > 100) {
            sendResponse('error', 'Invalid input data');
        }
        
        try {
            // Verify task belongs to teacher's subject
            $stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = ? AND subject = ?");
            $stmt->execute([$task_id, $_SESSION['subject']]);
            $task = $stmt->fetch();
            
            if (!$task) {
                sendResponse('error', 'Task not found or access denied');
            }
            
            $stmt = $pdo->prepare("UPDATE tasks SET grade = ?, feedback = ?, status = 'dinilai' WHERE id = ?");
            if ($stmt->execute([$grade, $feedback, $task_id])) {
                sendResponse('success', 'Grade updated successfully');
            } else {
                sendResponse('error', 'Failed to update grade');
            }
        } catch(PDOException $e) {
            sendResponse('error', 'Database error');
        }
        break;
        
    case 'get_statistics':
        try {
            $stats = [];
            
            if ($_SESSION['role'] === 'siswa') {
                $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM tasks WHERE student_id = ?");
                $stmt->execute([$_SESSION['user_id']]);
                $stats['total_tasks'] = $stmt->fetchColumn();
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as graded FROM tasks WHERE student_id = ? AND grade IS NOT NULL");
                $stmt->execute([$_SESSION['user_id']]);
                $stats['graded_tasks'] = $stmt->fetchColumn();
                
                $stmt = $pdo->prepare("SELECT AVG(grade) as avg_grade FROM tasks WHERE student_id = ? AND grade IS NOT NULL");
                $stmt->execute([$_SESSION['user_id']]);
                $stats['average_grade'] = round($stmt->fetchColumn(), 2);
                
            } elseif ($_SESSION['role'] === 'guru') {
                $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM tasks WHERE subject = ?");
                $stmt->execute([$_SESSION['subject']]);
                $stats['total_tasks'] = $stmt->fetchColumn();
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as pending FROM tasks WHERE subject = ? AND grade IS NULL");
                $stmt->execute([$_SESSION['subject']]);
                $stats['pending_tasks'] = $stmt->fetchColumn();
                
            } else {
                $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM users WHERE role != 'admin'");
                $stmt->execute();
                $stats['total_users'] = $stmt->fetchColumn();
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM tasks");
                $stmt->execute();
                $stats['total_tasks'] = $stmt->fetchColumn();
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as students FROM users WHERE role = 'siswa'");
                $stmt->execute();
                $stats['total_students'] = $stmt->fetchColumn();
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as teachers FROM users WHERE role = 'guru'");
                $stmt->execute();
                $stats['total_teachers'] = $stmt->fetchColumn();
            }
            
            sendResponse('success', 'Statistics retrieved successfully', $stats);
        } catch(PDOException $e) {
            sendResponse('error', 'Database error');
        }
        break;
        
    default:
        sendResponse('error', 'Invalid action');
}
?>