<?php
session_start();
require_once 'config.php';

// Set JSON header for all responses
header('Content-Type: application/json; charset=utf-8');

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

$action = $_GET['action'] ?? $_POST['action'] ?? null;
$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'] ?? '';

$rawInput = file_get_contents('php://input');
$requestData = null;
if (!empty($rawInput)) {
    $decoded = json_decode($rawInput, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $requestData = $decoded;
        if (!$action && isset($decoded['action'])) {
            $action = $decoded['action'];
        }
    }
}

// Helper function to get portfolio data with counter
function getPortfolioData($conn, $user_id, $divisi, $semester, $setting_type) {
    $stmt = $conn->prepare("
        SELECT COALESCE(counter, 0) as next_nomor 
        FROM portfolio_counter
        WHERE user_id = ? AND divisi = ? AND semester = ? AND setting_type = ?
    ");
    $stmt->bind_param("isis", $user_id, $divisi, $semester, $setting_type);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    
    return $row ? ($row['next_nomor'] + 1) : 1;
}

function canAccessPortfolioUser($conn, $user_role, $current_user_id, $current_specialization, $target_user_id, $portfolio_supervisor_initial = '') {
    if ($target_user_id === $current_user_id) {
        return true;
    }
    if ($user_role === 'admin') {
        return true;
    }
    if ($user_role !== 'dosen') {
        return false;
    }

    $stmt = $conn->prepare("SELECT role, specialization FROM users WHERE id = ? AND is_active = TRUE");
    $stmt->bind_param("i", $target_user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    if (!$user) {
        return false;
    }

    // Check if trainee's specialization matches and portfolio's supervisor_initial should match dosen's supervisor_initial
    if ($user['role'] === 'trainee' && $user['specialization'] === $current_specialization) {
        // If portfolio has supervisor_initial, check if it matches current dosen's supervisor_initial
        if (!empty($portfolio_supervisor_initial)) {
            $stmt = $conn->prepare("SELECT supervisor_initial FROM users WHERE id = ? AND is_active = TRUE");
            $stmt->bind_param("i", $current_user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $dosen = $result->fetch_assoc();
            $stmt->close();
            
            if (!$dosen || $dosen['supervisor_initial'] !== $portfolio_supervisor_initial) {
                return false;
            }
        }
        return true;
    }
    
    return false;
}

switch ($action) {
    case 'get_supervisors':
        // Get list of supervisors (dosen) with their initials
        $stmt = $conn->prepare("
            SELECT id, full_name, supervisor_initial, specialization 
            FROM users 
            WHERE role = 'dosen' AND is_active = TRUE AND supervisor_initial IS NOT NULL AND supervisor_initial != ''
            ORDER BY full_name ASC
        ");
        $stmt->execute();
        $result = $stmt->get_result();
        
        $supervisors = [];
        while ($row = $result->fetch_assoc()) {
            $supervisors[] = [
                'id' => $row['id'],
                'full_name' => $row['full_name'],
                'supervisor_initial' => $row['supervisor_initial'],
                'specialization' => $row['specialization']
            ];
        }
        $stmt->close();
        
        echo json_encode(['success' => true, 'data' => $supervisors]);
        break;

    case 'get_next_nomor':
        // Get next nomor for a specific portfolio entry
        $divisi = sanitize($_GET['divisi'] ?? '');
        $semester = (int)($_GET['semester'] ?? 0);
        $setting_type = sanitize($_GET['setting_type'] ?? '');
        
        $next_nomor = getPortfolioData($conn, $user_id, $divisi, $semester, $setting_type);
        echo json_encode(['success' => true, 'nomor' => $next_nomor]);
        break;

    case 'create':
        // Create new portfolio entry
        try {
            $data = $requestData;
            
            if (!$data) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Invalid JSON input']);
                exit;
            }
            
            $divisi = sanitize($data['divisi'] ?? '');
            $semester = (int)($data['semester'] ?? 0);
            $setting_type = sanitize($data['setting_type'] ?? '');
            $tanggal = sanitize($data['tanggal'] ?? '');
            $identifikasi_pasien = sanitize($data['identifikasi_pasien'] ?? '');
            $nama_pasien = sanitize($data['nama_pasien'] ?? '');
            $nomor_rm = sanitize($data['nomor_rm'] ?? '');
            $umur = isset($data['umur']) && $data['umur'] !== '' ? (int)($data['umur']) : 0;
            $paritas = sanitize($data['paritas'] ?? '');
            $alamat = sanitize($data['alamat'] ?? '');
            $diagnosis = sanitize($data['diagnosis'] ?? '');
            $tatalaksana = sanitize($data['tatalaksana'] ?? '');
            $kompetenszi = sanitize($data['kompetenszi'] ?? '');
            $supervisor_name = sanitize($data['supervisor_name'] ?? '');
            $supervisor_initial = sanitize($data['supervisor_initial'] ?? '');
            // Signature is already base64 string without prefix
            $trainee_signature = isset($data['trainee_signature']) ? $data['trainee_signature'] : '';
            
            // Get next nomor (only for current user)
            $nomor = getPortfolioData($conn, $user_id, $divisi, $semester, $setting_type);
            if (!is_int($nomor)) {
                $nomor = (int)$nomor;
            }
            if ($nomor <= 0) {
                $nomor = 1;
            }
            
            // Validate required fields
            if (empty($divisi) || empty($semester) || empty($setting_type) || empty($tanggal)) {
                throw new Exception('Missing required fields: divisi=' . $divisi . ', semester=' . $semester . ', setting_type=' . $setting_type . ', tanggal=' . $tanggal);
            }
            
            // Debug log
            error_log("Portfolio create: user_id=$user_id, divisi=$divisi, semester=$semester, setting_type=$setting_type, nomor=$nomor");
            
            // Insert portfolio
            $stmt = $conn->prepare("
                INSERT INTO portfolio (
                    user_id, divisi, semester, setting_type, nomor, tanggal,
                    identifikasi_pasien, nama_pasien, nomor_rm, umur, paritas, alamat,
                    diagnosis, tatalaksana, kompetenszi,
                    supervisor_name, supervisor_initial, trainee_signature, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft')
            ");
            
            if (!$stmt) {
                throw new Exception('Prepare failed: ' . $conn->error);
            }
            
            $signature_data = preg_replace('#^data:image/\w+;base64,#i', '', $trainee_signature);
            $signature_blob = $signature_data ? $signature_data : '';

            $bind_result = $stmt->bind_param(
                "isisssssssisssssss",
                $user_id, $divisi, $semester, $setting_type, $nomor, $tanggal,
                $identifikasi_pasien, $nama_pasien, $nomor_rm, $umur, $paritas, $alamat,
                $diagnosis, $tatalaksana, $kompetenszi,
                $supervisor_name, $supervisor_initial, $signature_blob
            );
            
            if (!$bind_result) {
                throw new Exception('Bind failed: ' . $stmt->error);
            }
            
            error_log("About to execute with nomor=$nomor, divisi=$divisi");
            
            if ($stmt->execute()) {
                $insert_id = $conn->insert_id;
                error_log("Insert successful, ID=$insert_id");
                
                // Update counter after successful insert
                $counter_stmt = $conn->prepare("
                    INSERT INTO portfolio_counter (user_id, divisi, semester, setting_type, counter)
                    VALUES (?, ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE counter = ?
                ");
                $counter_stmt->bind_param("isisii", $user_id, $divisi, $semester, $setting_type, $nomor, $nomor);
                $counter_stmt->execute();
                $counter_stmt->close();
                
                echo json_encode(['success' => true, 'id' => $insert_id, 'nomor' => $nomor]);
            } else {
                $error_msg = $stmt->error;
                error_log("Execute failed: $error_msg");
                throw new Exception('Execute failed: ' . $error_msg);
            }
            $stmt->close();
            
        } catch (Exception $e) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        break;

    case 'get':
        // Get single portfolio entry
        $id = (int)($_GET['id'] ?? 0);
        
        $stmt = $conn->prepare("
            SELECT * FROM portfolio
            WHERE id = ? AND user_id = ?
        ");
        $stmt->bind_param("ii", $id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $row = $result->fetch_assoc();
        if (!$row) {
            // Fallback for dosen/admin access
            $stmt->close();
            $stmt = $conn->prepare("SELECT * FROM portfolio WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
        }

        if ($row && canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, (int)$row['user_id'], $row['supervisor_initial'] ?? '')) {
            // Stored as base64 without prefix; add data URL prefix for output
            if ($row['trainee_signature']) {
                $row['trainee_signature'] = 'data:image/png;base64,' . $row['trainee_signature'];
            }
            if ($row['dpjp_signature']) {
                $row['dpjp_signature'] = 'data:image/png;base64,' . $row['dpjp_signature'];
            }
            echo json_encode(['success' => true, 'data' => $row]);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Portfolio not found']);
        }
        $stmt->close();
        break;

    case 'list_all':
        // Get portfolio list for all accessible users (used by dosen/admin views)
        $user_ids = [];

        if ($user_role === 'trainee') {
            $user_ids = [$user_id];
        } else if ($user_role === 'dosen') {
            $stmt = $conn->prepare("SELECT id FROM users WHERE role = 'trainee' AND specialization = ? AND is_active = TRUE");
            $stmt->bind_param("s", $user_specialization);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $user_ids[] = $row['id'];
            }
            $stmt->close();
        } else if ($user_role === 'admin') {
            $stmt = $conn->prepare("SELECT id FROM users WHERE role = 'trainee' AND is_active = TRUE");
            $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;
        }

        $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
        $types = str_repeat('i', count($user_ids));

        // Build query - show all portfolio items for trainee users
        $query = "SELECT p.id, p.user_id, u.full_name AS user_name, u.specialization, u.semester, p.divisi, p.semester, p.setting_type, p.nomor, p.tanggal, p.diagnosis, p.tatalaksana, p.kompetenszi, p.supervisor_name, p.supervisor_initial, p.dpjp_verified, p.dpjp_verified_by, p.dpjp_verified_at, p.status, p.created_at, p.updated_at FROM portfolio p JOIN users u ON p.user_id = u.id WHERE p.user_id IN ($placeholders)";
        
        $query .= " ORDER BY p.tanggal DESC, p.nomor DESC";

        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$user_ids);
        $stmt->execute();
        $result = $stmt->get_result();

        $items = [];
        while ($row = $result->fetch_assoc()) {
            $items[] = $row;
        }

        echo json_encode(['success' => true, 'data' => $items]);
        $stmt->close();
        break;

    case 'list':
        // Get portfolio list with filters
        $divisi = sanitize($_GET['divisi'] ?? '');
        $semester = (int)($_GET['semester'] ?? 0);
        $setting_type = sanitize($_GET['setting_type'] ?? '');
        $target_user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : $user_id;
        $verified_only = isset($_GET['verified_only']) && $_GET['verified_only'] === '1';

        if (!canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, $target_user_id)) {
            http_response_code(403);
                echo json_encode(['success' => false, 'error' => 'Forbidden']);
            exit;
        }
        
            $query = "SELECT p.id, p.user_id, u.full_name AS user_name, p.divisi, p.semester, p.setting_type, p.nomor, p.tanggal, p.identifikasi_pasien, p.nama_pasien, p.nomor_rm, p.umur, p.paritas, p.alamat, p.diagnosis, p.tatalaksana, p.kompetenszi, p.supervisor_name, p.trainee_signature, p.dpjp_signature, p.dpjp_verified, p.dpjp_verified_by, p.dpjp_verified_at, p.status, p.created_at, p.updated_at FROM portfolio p JOIN users u ON p.user_id = u.id WHERE p.user_id = ?";
        $params = [$target_user_id];
        $types = "i";
        
        if ($divisi) {
            $query .= " AND p.divisi = ?";
            $params[] = $divisi;
            $types .= "s";
        }
        if ($semester > 0) {
            $query .= " AND p.semester = ?";
            $params[] = $semester;
            $types .= "i";
        }
        if ($setting_type) {
            $query .= " AND p.setting_type = ?";
            $params[] = $setting_type;
            $types .= "s";
        }
        
        // Filter for verified/signed items only when requested
        if ($verified_only) {
            $query .= " AND (p.dpjp_verified = TRUE OR p.status = 'verified')";
        }
        
        $query .= " ORDER BY tanggal DESC, nomor DESC";
        
        $stmt = $conn->prepare($query);
        if (count($params) > 0) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        $items = [];
        while ($row = $result->fetch_assoc()) {
            $items[] = $row;
        }
        
        echo json_encode(['success' => true, 'data' => $items]);
        $stmt->close();
        break;

    case 'update':
        // Update portfolio entry
        $data = $requestData;
        if (!$data) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON input']);
            exit;
        }
        $id = $data['id'] ?? 0;
        
        // Verify ownership / access
        $stmt = $conn->prepare("SELECT user_id FROM portfolio WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        
        if (!$row || !canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, (int)$row['user_id'])) {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden']);
            exit;
        }
        
        $updates = [];
        $params = [];
        $types = "";
        
        $fields = ['tanggal', 'identifikasi_pasien', 'nama_pasien', 'nomor_rm', 'umur', 'paritas', 'alamat', 'diagnosis', 'tatalaksana', 'kompetenszi', 'supervisor_name', 'supervisor_initial', 'status'];
        
        foreach ($fields as $field) {
            if (isset($data[$field])) {
                $updates[] = "$field = ?";
                if ($field === 'umur' && $data[$field] !== '') {
                    $params[] = (int)$data[$field];
                    $types .= "i";
                } else {
                    $params[] = sanitize($data[$field]);
                    $types .= "s";
                }
            }
        }
        
        if (isset($data['trainee_signature']) && $data['trainee_signature']) {
            $updates[] = "trainee_signature = ?";
            $signature_data = preg_replace('#^data:image/\w+;base64,#i', '', $data['trainee_signature']);
            $params[] = $signature_data;
            $types .= "s";
        }
        
        if (empty($updates)) {
            echo json_encode(['error' => 'No fields to update']);
            exit;
        }
        
        $params[] = $id;
        $types .= "i";
        
        $query = "UPDATE portfolio SET " . implode(", ", $updates) . " WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => $stmt->error]);
        }
        $stmt->close();
        break;

    case 'fetch':
        // Fetch single portfolio entry for viewing
        $id = (int)($_POST['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Invalid ID']);
            exit;
        }
        
        $stmt = $conn->prepare("
            SELECT id, nomor, tanggal, identifikasi_pasien, nama_pasien, nomor_rm, 
                   diagnosis, tatalaksana, kompetenszi, supervisor_name, supervisor_initial, 
                   status, dpjp_verified, trainee_signature, dpjp_signature, user_id
            FROM portfolio WHERE id = ?
        ");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        
        if (!$row) {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'Portfolio not found']);
            exit;
        }
        
        // Check access
        if (!canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, (int)$row['user_id'])) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => 'Forbidden']);
            exit;
        }
        
        // Format signatures as data URLs
        if ($row['trainee_signature'] && !strpos($row['trainee_signature'], 'data:')) {
            $row['trainee_signature'] = 'data:image/png;base64,' . $row['trainee_signature'];
        }
        if ($row['dpjp_signature'] && !strpos($row['dpjp_signature'], 'data:')) {
            $row['dpjp_signature'] = 'data:image/png;base64,' . $row['dpjp_signature'];
        }
        
        echo json_encode(['success' => true, 'data' => $row]);
        break;

    case 'delete':
        // Delete portfolio entry
        $id = (int)($_POST['id'] ?? 0);
        
        $stmt = $conn->prepare("SELECT user_id FROM portfolio WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        
        if (!$row || !canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, (int)$row['user_id'])) {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden']);
            exit;
        }
        
        $stmt = $conn->prepare("DELETE FROM portfolio WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => $stmt->error]);
        }
        $stmt->close();
        break;

    case 'submit_for_verification':
        // Submit portfolio for DPJP verification
        $id = (int)($_POST['id'] ?? 0);
        
        $stmt = $conn->prepare("SELECT user_id FROM portfolio WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        
        if (!$row || !canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, (int)$row['user_id'])) {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden']);
            exit;
        }
        
        $stmt = $conn->prepare("UPDATE portfolio SET status = 'submitted' WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => $stmt->error]);
        }
        $stmt->close();
        break;

    case 'verify_dpjp':
        // DPJP signature and verification (dosen only)
        if ($user_role !== 'dosen' && $user_role !== 'admin') {
            http_response_code(403);
            echo json_encode(['error' => 'Only DPJP can verify']);
            exit;
        }
        
        $data = $requestData;
        if (!$data) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid JSON input']);
            exit;
        }
        $id = $data['id'] ?? 0;
        $dpjp_signature = $data['dpjp_signature'] ?? null;

        $stmt = $conn->prepare("SELECT user_id, supervisor_initial FROM portfolio WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();

        if (!$row || !canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, (int)$row['user_id'], $row['supervisor_initial'] ?? '')) {
            http_response_code(403);
            echo json_encode(['error' => 'Forbidden']);
            exit;
        }
        
        $signature_blob = '';
        if ($dpjp_signature) {
            $signature_data = preg_replace('#^data:image/\w+;base64,#i', '', $dpjp_signature);
            $signature_blob = $signature_data;
        }
        
        $stmt = $conn->prepare("
            UPDATE portfolio 
            SET dpjp_signature = ?, dpjp_verified = TRUE, dpjp_verified_by = ?, dpjp_verified_at = NOW(), status = 'verified'
            WHERE id = ?
        ");
        $stmt->bind_param("sii", $signature_blob, $user_id, $id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => $stmt->error]);
        }
        $stmt->close();
        break;

    case 'get_by_month':
        // Get portfolio entries for a specific month (for calendar display)
        $year = (int)($_GET['year'] ?? date('Y'));
        $month = (int)($_GET['month'] ?? date('m'));
        $target_user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : $user_id;

        if (!canAccessPortfolioUser($conn, $user_role, $user_id, $user_specialization, $target_user_id)) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => 'Forbidden']);
            exit;
        }

        $month_str = str_pad($month, 2, '0', STR_PAD_LEFT);
        $start_date = "$year-$month_str-01";
        $end_date = date('Y-m-t', strtotime($start_date));

        $stmt = $conn->prepare("
            SELECT 
                p.id, 
                p.tanggal, 
                p.divisi, 
                p.semester, 
                p.setting_type, 
                p.nomor, 
                p.nama_pasien, 
                p.diagnosis,
                p.dpjp_verified,
                p.status
            FROM portfolio p
            WHERE p.user_id = ? 
            AND p.tanggal >= ? 
            AND p.tanggal <= ?
            ORDER BY p.tanggal, p.nomor
        ");
        $stmt->bind_param("iss", $target_user_id, $start_date, $end_date);
        $stmt->execute();
        $result = $stmt->get_result();

        $items = [];
        while ($row = $result->fetch_assoc()) {
            $items[] = $row;
        }

        echo json_encode(['success' => true, 'data' => $items]);
        $stmt->close();
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
}
?>
