<?php
session_start();
require 'config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'] ?? 'trainee';
$user_specialization = $_SESSION['user_data']['specialization'] ?? '';
$user_supervisor_initial = $_SESSION['user_data']['supervisor_initial'] ?? '';

$method = $_SERVER['REQUEST_METHOD'];

// GET: Fetch logbooks based on user role
if ($method === 'GET') {
    
    // Get all logbooks that user has access to
    if (isset($_GET['action']) && $_GET['action'] === 'get_logbooks') {
        $year = intval($_GET['year'] ?? date('Y'));
        $month = intval($_GET['month'] ?? date('m'));
        $include_all = isset($_GET['all']) && $_GET['all'] === '1';
        $sort_unverified = isset($_GET['sort']) && $_GET['sort'] === 'unverified_first';
        
        $start_date = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
        $end_date = date('Y-m-t', strtotime($start_date));
        
        // Determine which user IDs this user can access based on their role
        $user_ids = [];
        
        if ($user_role === 'trainee') {
            // Trainee can only see their own logs
            $user_ids = [$user_id];
        } 
        else if ($user_role === 'dosen') {
            // Dosen can see their own logs and all trainees with the same subspesialisasi
            $query = "
                SELECT DISTINCT u.id 
                FROM users u 
                WHERE (u.id = ? OR (u.role = 'trainee' AND u.specialization = ?))
            ";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("is", $user_id, $user_specialization);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $user_ids[] = $row['id'];
            }
            $stmt->close();
        }
        else if ($user_role === 'admin') {
            // Admin can see all logs
            $query = "SELECT id FROM users WHERE is_active = TRUE";
            $stmt = $conn->prepare($query);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $user_ids[] = $row['id'];
            }
            $stmt->close();
        }
        
        if (empty($user_ids)) {
            echo json_encode(['success' => true, 'data' => []]);
            exit();
        }
        
        // Build placeholders for IN clause
        $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
        
        // Fetch logs with user information
        $query = "
            SELECT 
                l.id,
                l.user_id,
                u.username,
                u.full_name,
                u.specialization,
                u.semester,
                l.activity_type_id,
                at.type_name,
                lc.category_name,
                l.log_date,
                l.title,
                l.description,
                l.location,
                l.supervisor_name,
                l.supervisor_initial,
                l.case_count,
                l.status,
                l.dpjp_verified,
                l.dpjp_verified_by,
                l.dpjp_verified_at,
                l.created_at,
                l.updated_at
            FROM logs l
            JOIN users u ON l.user_id = u.id
            JOIN activity_types at ON l.activity_type_id = at.id
            JOIN log_categories lc ON at.category_id = lc.id
            WHERE l.user_id IN ($placeholders)
        ";
        
        if (!$include_all) {
            $query .= " AND l.log_date BETWEEN ? AND ?";
        }
        
        if ($sort_unverified) {
            $query .= " ORDER BY (l.dpjp_verified = TRUE) ASC, l.log_date DESC, u.full_name";
        } else {
            $query .= " ORDER BY l.log_date DESC, u.full_name";
        }
        
        // Build types string and parameter array
        $types = str_repeat('i', count($user_ids));
        $params = $user_ids;
        
        if (!$include_all) {
            $types .= 'ss';
            $params = array_merge($params, [$start_date, $end_date]);
        }
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        $logs = [];
        while ($row = $result->fetch_assoc()) {
            $logs[] = $row;
        }
        
        echo json_encode(['success' => true, 'data' => $logs]);
        $stmt->close();
    }
    
    // Get list of trainees available to current dosen/admin
    else if (isset($_GET['action']) && $_GET['action'] === 'get_trainees') {
        $trainees = [];
        
        if ($user_role === 'dosen') {
            // Dosen can see trainees in their subspesialisasi
            $query = "
                SELECT id, username, full_name, specialization, semester 
                FROM users 
                WHERE role = 'trainee' AND specialization = ?
                ORDER BY full_name
            ";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("s", $user_specialization);
        }
        else if ($user_role === 'admin') {
            // Admin can see all trainees
            $query = "
                SELECT id, username, full_name, specialization, semester 
                FROM users 
                WHERE role = 'trainee'
                ORDER BY specialization, full_name
            ";
            $stmt = $conn->prepare($query);
        }
        else {
            // Trainee cannot view other trainees' list
            echo json_encode(['success' => true, 'data' => []]);
            exit();
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $trainees[] = $row;
        }
        
        echo json_encode(['success' => true, 'data' => $trainees]);
        $stmt->close();
    }
    
    // Get logbook stats based on role
    else if (isset($_GET['action']) && $_GET['action'] === 'get_stats') {
        $year = intval($_GET['year'] ?? date('Y'));
        
        // Determine which user IDs this user can access
        $user_ids = [];
        
        if ($user_role === 'trainee') {
            $user_ids = [$user_id];
        }
        else if ($user_role === 'dosen') {
            $query = "
                SELECT DISTINCT u.id 
                FROM users u 
                WHERE (u.id = ? OR (u.role = 'trainee' AND u.specialization = ?))
            ";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("is", $user_id, $user_specialization);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $user_ids[] = $row['id'];
            }
            $stmt->close();
        }
        else if ($user_role === 'admin') {
            $query = "SELECT id FROM users WHERE is_active = TRUE";
            $stmt = $conn->prepare($query);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $user_ids[] = $row['id'];
            }
            $stmt->close();
        }
        
        if (empty($user_ids)) {
            echo json_encode(['success' => true, 'data' => [
                'total_logs' => 0,
                'total_cases' => 0,
                'total_users' => 0
            ]]);
            exit();
        }
        
        $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
        
        $query = "
            SELECT 
                COUNT(*) as total_logs,
                SUM(case_count) as total_cases,
                COUNT(DISTINCT user_id) as total_users
            FROM logs
            WHERE user_id IN ($placeholders) AND YEAR(log_date) = ?
        ";
        
        $types = str_repeat('i', count($user_ids)) . 'i';
        $stmt = $conn->prepare($query);
        
        $params = array_merge($user_ids, [$year]);
        $stmt->bind_param($types, ...$params);
        
        $stmt->execute();
        $stats = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        // Count portfolio entries as cases
        $portfolio_query = "
            SELECT COUNT(*) as portfolio_cases
            FROM portfolio
            WHERE user_id IN ($placeholders) AND YEAR(tanggal) = ?
        ";
        $portfolio_stmt = $conn->prepare($portfolio_query);
        $portfolio_stmt->bind_param($types, ...$params);
        $portfolio_stmt->execute();
        $portfolio_stats = $portfolio_stmt->get_result()->fetch_assoc();
        $portfolio_stmt->close();

        $log_cases = (int)($stats['total_cases'] ?? 0);
        $portfolio_cases = (int)($portfolio_stats['portfolio_cases'] ?? 0);
        $stats['total_cases'] = $log_cases + $portfolio_cases;

        echo json_encode(['success' => true, 'data' => $stats]);
    }
    
    // GET: Get dosen statistics for dashboard
    else if ($_GET['action'] === 'get_dosen_stats') {
        if ($user_role !== 'dosen' && $user_role !== 'admin') {
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit();
        }
        
        $year = sanitize($_GET['year'] ?? date('Y'));
        $today = date('Y-m-d');
        
        // For admin, show all trainees; for dosen, show trainees with same specialization
        if ($user_role === 'admin') {
            // Admin: count all trainees
            $trainee_query = "
                SELECT COUNT(*) as total_trainees
                FROM users
                WHERE role = 'trainee' AND is_active = TRUE
            ";
            $trainee_stmt = $conn->prepare($trainee_query);
            $trainee_stmt->execute();
            $trainee_stats = $trainee_stmt->get_result()->fetch_assoc();
            $trainee_stmt->close();
            
            // Get all trainee IDs for stats
            $trainee_ids_query = "
                SELECT id FROM users
                WHERE role = 'trainee' AND is_active = TRUE
            ";
        } else {
            // Dosen: count trainees with same specialization
            $trainee_query = "
                SELECT COUNT(*) as total_trainees
                FROM users
                WHERE role = 'trainee' AND specialization = ? AND is_active = TRUE
            ";
            $trainee_stmt = $conn->prepare($trainee_query);
            $trainee_stmt->bind_param("s", $user_specialization);
            $trainee_stmt->execute();
            $trainee_stats = $trainee_stmt->get_result()->fetch_assoc();
            $trainee_stmt->close();
            
            // Get trainee IDs for dosen's specialization
            $trainee_ids_query = "
                SELECT id FROM users
                WHERE role = 'trainee' AND specialization = ? AND is_active = TRUE
            ";
        }
        
        // Get trainees user IDs for log verification stats
        $trainee_ids_stmt = $conn->prepare($trainee_ids_query);
        if ($user_role === 'dosen') {
            $trainee_ids_stmt->bind_param("s", $user_specialization);
        }
        $trainee_ids_stmt->execute();
        $trainee_ids_result = $trainee_ids_stmt->get_result();
        
        $trainee_ids = [];
        while ($row = $trainee_ids_result->fetch_assoc()) {
            $trainee_ids[] = $row['id'];
        }
        $trainee_ids_stmt->close();
        
        $unverified = 0;
        $verified = 0;
        $today_activities = 0;
        
        if (!empty($trainee_ids)) {
            $placeholders = str_repeat('?,', count($trainee_ids) - 1) . '?';
            
            // Count unverified logs
            $unverified_query = "
                SELECT COUNT(*) as cnt FROM logs
                WHERE user_id IN ($placeholders) AND (dpjp_verified = FALSE OR dpjp_verified IS NULL) AND YEAR(log_date) = ?
            ";
            $unverified_stmt = $conn->prepare($unverified_query);
            $types = str_repeat('i', count($trainee_ids)) . 'i';
            $params = array_merge($trainee_ids, [$year]);
            $unverified_stmt->bind_param($types, ...$params);
            $unverified_stmt->execute();
            $unverified_result = $unverified_stmt->get_result()->fetch_assoc();
            $unverified = $unverified_result['cnt'] ?? 0;
            $unverified_stmt->close();
            
            // Count verified logs (only by this dosen/admin)
            $verified_query = "
                SELECT COUNT(*) as cnt FROM logs
                WHERE user_id IN ($placeholders) AND dpjp_verified = TRUE AND dpjp_verified_by = ? AND YEAR(log_date) = ?
            ";
            $verified_stmt = $conn->prepare($verified_query);
            $verified_params = array_merge($trainee_ids, [$user_id, $year]);
            $verified_types = str_repeat('i', count($trainee_ids)) . 'ii';
            $verified_stmt->bind_param($verified_types, ...$verified_params);
            $verified_stmt->execute();
            $verified_result = $verified_stmt->get_result()->fetch_assoc();
            $verified = $verified_result['cnt'] ?? 0;
            $verified_stmt->close();
            
            // Count activities today
            $today_query = "
                SELECT COUNT(*) as cnt FROM logs
                WHERE user_id IN ($placeholders) AND DATE(log_date) = ?
            ";
            $today_stmt = $conn->prepare($today_query);
            $today_types = str_repeat('i', count($trainee_ids)) . 's';
            $today_params = array_merge($trainee_ids, [$today]);
            $today_stmt->bind_param($today_types, ...$today_params);
            $today_stmt->execute();
            $today_result = $today_stmt->get_result()->fetch_assoc();
            $today_activities = $today_result['cnt'] ?? 0;
            $today_stmt->close();

            // Count unverified portfolio entries
            $portfolio_unverified_query = "
                SELECT COUNT(*) as cnt FROM portfolio
                WHERE user_id IN ($placeholders) AND (dpjp_verified = FALSE OR dpjp_verified IS NULL) AND YEAR(tanggal) = ?
            ";
            $portfolio_unverified_stmt = $conn->prepare($portfolio_unverified_query);
            $portfolio_unverified_stmt->bind_param($types, ...$params);
            $portfolio_unverified_stmt->execute();
            $portfolio_unverified_result = $portfolio_unverified_stmt->get_result()->fetch_assoc();
            $unverified += $portfolio_unverified_result['cnt'] ?? 0;
            $portfolio_unverified_stmt->close();

            // Count verified portfolio entries (only by this dosen/admin)
            $portfolio_verified_query = "
                SELECT COUNT(*) as cnt FROM portfolio
                WHERE user_id IN ($placeholders) AND dpjp_verified = TRUE AND dpjp_verified_by = ? AND YEAR(tanggal) = ?
            ";
            $portfolio_verified_stmt = $conn->prepare($portfolio_verified_query);
            $portfolio_verified_params = array_merge($trainee_ids, [$user_id, $year]);
            $portfolio_verified_types = str_repeat('i', count($trainee_ids)) . 'ii';
            $portfolio_verified_stmt->bind_param($portfolio_verified_types, ...$portfolio_verified_params);
            $portfolio_verified_stmt->execute();
            $portfolio_verified_result = $portfolio_verified_stmt->get_result()->fetch_assoc();
            $verified += $portfolio_verified_result['cnt'] ?? 0;
            $portfolio_verified_stmt->close();

            // Count portfolio activities today
            $portfolio_today_query = "
                SELECT COUNT(*) as cnt FROM portfolio
                WHERE user_id IN ($placeholders) AND DATE(tanggal) = ?
            ";
            $portfolio_today_stmt = $conn->prepare($portfolio_today_query);
            $portfolio_today_stmt->bind_param($today_types, ...$today_params);
            $portfolio_today_stmt->execute();
            $portfolio_today_result = $portfolio_today_stmt->get_result()->fetch_assoc();
            $today_activities += $portfolio_today_result['cnt'] ?? 0;
            $portfolio_today_stmt->close();
        }
        
        $dosen_stats = [
            'total_trainees' => (int)($trainee_stats['total_trainees'] ?? 0),
            'unverified_logs' => (int)$unverified,
            'verified_logs' => (int)$verified,
            'today_activities' => (int)$today_activities
        ];
        
        echo json_encode(['success' => true, 'data' => $dosen_stats]);
    }
}
else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>
