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

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

$method = $_SERVER['REQUEST_METHOD'];
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'] ?? 'trainee';
$user_specialization = $_SESSION['user_data']['specialization'] ?? '';

function canAccessLogUser($conn, $user_role, $current_user_id, $current_specialization, $target_user_id) {
    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;
    }

    return $user['role'] === 'trainee' && $user['specialization'] === $current_specialization;
}

function getLogOwnerId($conn, $log_id) {
    $stmt = $conn->prepare("SELECT user_id FROM logs WHERE id = ?");
    $stmt->bind_param("i", $log_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    return $row ? (int)$row['user_id'] : null;
}

function isAllowedGenericMenuKey($key) {
    $allowed = ['seminarWorkshop', 'publikasiIlmiah', 'penelitian', 'aktivitasPembelajaran'];
    return in_array($key, $allowed, true);
}

function ensureGenericMenuTableExists($conn) {
    static $initialized = false;
    if ($initialized) return;

    $sql = "
        CREATE TABLE IF NOT EXISTS generic_menu_tables (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            table_key VARCHAR(50) NOT NULL,
            rows_json LONGTEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_generic_menu_user_table (user_id, table_key),
            INDEX idx_generic_menu_user (user_id),
            CONSTRAINT fk_generic_menu_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ";

    $conn->query($sql);
    $initialized = true;
}

// GET: Fetch logs for specific month
if ($method === 'GET' && isset($_GET['action'])) {
    if ($_GET['action'] === 'get_logs') {
        $all = isset($_GET['all']) && $_GET['all'] === '1';
        $year = sanitize($_GET['year'] ?? date('Y'));
        $month = sanitize($_GET['month'] ?? date('m'));
        
        $start_date = "$year-$month-01";
        $end_date = date('Y-m-t', strtotime($start_date));
        
        if ($all) {
            $stmt = $conn->prepare("
                SELECT l.*, at.type_name, lc.category_name 
                FROM logs l
                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 = ?
                ORDER BY l.updated_at DESC, l.created_at DESC
            ");
            $stmt->bind_param("i", $user_id);
        } else {
            $stmt = $conn->prepare("
                SELECT l.*, at.type_name, lc.category_name 
                FROM logs l
                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 = ? AND l.log_date BETWEEN ? AND ?
                ORDER BY l.log_date DESC
            ");
            $stmt->bind_param("iss", $user_id, $start_date, $end_date);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        $logs = [];
        while ($row = $result->fetch_assoc()) {
            $logs[] = $row;
        }
        
        echo json_encode(['success' => true, 'data' => $logs]);
        $stmt->close();
    }
    
    // GET: Get log statistics for dashboard
    else if ($_GET['action'] === 'get_statistics') {
        $year = sanitize($_GET['year'] ?? date('Y'));
        
        $stmt = $conn->prepare("
            SELECT 
                COUNT(*) as total_logs,
                COUNT(DISTINCT DATE(log_date)) as days_logged,
                SUM(case_count) as total_cases
            FROM logs
            WHERE user_id = ? AND YEAR(log_date) = ?
        ");
        $stmt->bind_param("ii", $user_id, $year);
        $stmt->execute();
        $stats = $stmt->get_result()->fetch_assoc();
        
        echo json_encode(['success' => true, 'data' => $stats]);
        $stmt->close();
    }
    
    // GET: Get activity types for dropdown
    else if ($_GET['action'] === 'get_activity_types') {
        $stmt = $conn->prepare("
            SELECT at.id, at.type_name, lc.category_name
            FROM activity_types at
            JOIN log_categories lc ON at.category_id = lc.id
            ORDER BY lc.category_name, at.type_name
        ");
        $stmt->execute();
        $result = $stmt->get_result();
        
        $activities = [];
        while ($row = $result->fetch_assoc()) {
            $activities[] = $row;
        }
        
        echo json_encode(['success' => true, 'data' => $activities]);
        $stmt->close();
    }

    // GET: Get generic menu table rows (Seminar, Publikasi, Penelitian, Aktivitas)
    else if ($_GET['action'] === 'get_generic_menu_table') {
        $table_key = sanitize($_GET['table_key'] ?? '');

        ensureGenericMenuTableExists($conn);

        if (!isAllowedGenericMenuKey($table_key)) {
            echo json_encode(['success' => false, 'message' => 'Table key tidak valid']);
            exit();
        }

        $stmt = $conn->prepare("SELECT rows_json FROM generic_menu_tables WHERE user_id = ? AND table_key = ? LIMIT 1");
        $stmt->bind_param("is", $user_id, $table_key);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();

        $rows = [];
        if ($row && !empty($row['rows_json'])) {
            $decoded = json_decode($row['rows_json'], true);
            if (is_array($decoded)) {
                $rows = $decoded;
            }
        }

        echo json_encode(['success' => true, 'data' => $rows]);
    }
}

// POST: Save new log
else if ($method === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_log') {
        $activity_type_id = intval($_POST['activity_type_id'] ?? 0);
        $log_date = sanitize($_POST['log_date'] ?? '');
        $title = sanitize($_POST['title'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $location = sanitize($_POST['location'] ?? '');
        $supervisor_name = sanitize($_POST['supervisor_name'] ?? '');
        $supervisor_initial = sanitize($_POST['supervisor_initial'] ?? '');
        $case_count = intval($_POST['case_count'] ?? 1);
        
        if (empty($title) || empty($log_date) || empty($activity_type_id)) {
            echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
            exit();
        }
        
        $stmt = $conn->prepare("
            INSERT INTO logs (user_id, activity_type_id, log_date, title, description, location, supervisor_name, supervisor_initial, case_count)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("iisssssi", $user_id, $activity_type_id, $log_date, $title, $description, $location, $supervisor_name, $supervisor_initial, $case_count);
        
        if ($stmt->execute()) {
            $log_id = $conn->insert_id;
            
            // Save procedures if provided
            if (!empty($_POST['procedures'])) {
                $procedures = json_decode($_POST['procedures'], true);
                foreach ($procedures as $proc) {
                    $proc_name = sanitize($proc['name'] ?? '');
                    $proc_count = intval($proc['count'] ?? 1);
                    if (!empty($proc_name)) {
                        $proc_stmt = $conn->prepare("INSERT INTO procedures (log_id, procedure_name, procedure_count) VALUES (?, ?, ?)");
                        $proc_stmt->bind_param("isi", $log_id, $proc_name, $proc_count);
                        $proc_stmt->execute();
                        $proc_stmt->close();
                    }
                }
            }
            
            echo json_encode(['success' => true, 'message' => 'Log berhasil disimpan', 'log_id' => $log_id]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menyimpan log']);
        }
        
        $stmt->close();
    }

    else if ($_POST['action'] === 'update_log') {
        $log_id = intval($_POST['log_id'] ?? 0);
        if ($log_id <= 0) {
            echo json_encode(['success' => false, 'message' => 'Log ID tidak valid']);
            exit();
        }

        $owner_id = getLogOwnerId($conn, $log_id);
        if (!$owner_id || !canAccessLogUser($conn, $user_role, $user_id, $user_specialization, $owner_id)) {
            echo json_encode(['success' => false, 'message' => 'Akses ditolak']);
            exit();
        }

        $activity_type_id = intval($_POST['activity_type_id'] ?? 0);
        $log_date = sanitize($_POST['log_date'] ?? '');
        $title = sanitize($_POST['title'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $location = sanitize($_POST['location'] ?? '');
        $supervisor_name = sanitize($_POST['supervisor_name'] ?? '');
        $supervisor_initial = sanitize($_POST['supervisor_initial'] ?? '');
        $case_count = intval($_POST['case_count'] ?? 1);

        if (empty($title) || empty($log_date) || empty($activity_type_id)) {
            echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
            exit();
        }

        $stmt = $conn->prepare("
            UPDATE logs
            SET activity_type_id = ?, log_date = ?, title = ?, description = ?, location = ?, supervisor_name = ?, supervisor_initial = ?, case_count = ?
            WHERE id = ?
        ");
        $stmt->bind_param("issssssii", $activity_type_id, $log_date, $title, $description, $location, $supervisor_name, $supervisor_initial, $case_count, $log_id);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Log berhasil diperbarui']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal memperbarui log']);
        }
        $stmt->close();
    }

    else if ($_POST['action'] === 'verify_log') {
        if ($user_role !== 'dosen' && $user_role !== 'admin') {
            echo json_encode(['success' => false, 'message' => 'Akses ditolak']);
            exit();
        }

        $log_id = intval($_POST['log_id'] ?? 0);
        $dpjp_signature = $_POST['dpjp_signature'] ?? '';
        $supervisor_note = sanitize($_POST['supervisor_note'] ?? '');

        if ($log_id <= 0) {
            echo json_encode(['success' => false, 'message' => 'Log ID tidak valid']);
            exit();
        }

        // Get log details including supervisor_initial
        $stmt = $conn->prepare("SELECT user_id, supervisor_initial FROM logs WHERE id = ?");
        $stmt->bind_param("i", $log_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $log = $result->fetch_assoc();
        $stmt->close();

        if (!$log) {
            echo json_encode(['success' => false, 'message' => 'Log tidak ditemukan']);
            exit();
        }

        $owner_id = $log['user_id'];
        if (!canAccessLogUser($conn, $user_role, $user_id, $user_specialization, $owner_id)) {
            echo json_encode(['success' => false, 'message' => 'Akses ditolak']);
            exit();
        }

        // For dosen, validate supervisor_initial matches
        if ($user_role === 'dosen') {
            $user_supervisor_initial = $_SESSION['user_data']['supervisor_initial'] ?? '';
            $log_supervisor_initial = $log['supervisor_initial'] ?? '';
            
            if (!empty($user_supervisor_initial) && $user_supervisor_initial !== $log_supervisor_initial) {
                echo json_encode(['success' => false, 'message' => 'Anda hanya dapat memverifikasi log dengan inisial supervisor yang sesuai']);
                exit();
            }
        }

        $signature_data = '';
        if (!empty($dpjp_signature)) {
            $signature_data = preg_replace('#^data:image/\w+;base64,#i', '', $dpjp_signature);
        }

        $stmt = $conn->prepare("
            UPDATE logs
            SET dpjp_signature = ?, dpjp_verified = TRUE, dpjp_verified_by = ?, dpjp_verified_at = NOW(), status = 'approved', supervisor_note = ?
            WHERE id = ?
        ");
        $stmt->bind_param("sisi", $signature_data, $user_id, $supervisor_note, $log_id);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Log berhasil diverifikasi']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal verifikasi log']);
        }
        $stmt->close();
    }

    // POST: Save generic menu table rows (replace all rows per user/table)
    else if ($_POST['action'] === 'save_generic_menu_table') {
        $table_key = sanitize($_POST['table_key'] ?? '');
        $rows_json = $_POST['rows_json'] ?? '[]';

        ensureGenericMenuTableExists($conn);

        if (!isAllowedGenericMenuKey($table_key)) {
            echo json_encode(['success' => false, 'message' => 'Table key tidak valid']);
            exit();
        }

        $decoded = json_decode($rows_json, true);
        if (!is_array($decoded)) {
            echo json_encode(['success' => false, 'message' => 'Format data tidak valid']);
            exit();
        }

        $normalized_json = json_encode($decoded, JSON_UNESCAPED_UNICODE);

        $stmt = $conn->prepare("INSERT INTO generic_menu_tables (user_id, table_key, rows_json) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE rows_json = VALUES(rows_json), updated_at = CURRENT_TIMESTAMP");
        $stmt->bind_param("iss", $user_id, $table_key, $normalized_json);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Data tabel berhasil disimpan']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menyimpan data tabel']);
        }
        $stmt->close();
    }
}

else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>
