<?php
// This file is part of the Studyplan plugin for Moodle
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.

/**
 * Privacy information metadata
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan\privacy;

use core_privacy\local\metadata\collection;
use core_privacy\local\request\userlist;
use core_privacy\local\request\contextlist;
use core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\approved_userlist;
use core_privacy\local\request\deletion_criteria;
use core_privacy\local\request\writer;
use core_privacy\local\request\helper;
use core_privacy\local\request\transform;
use tool_dataprivacy\context_instance;
use core\context;
use core\context\system as context_system;
use local_treestudyplan\contextinfo;
use local_treestudyplan\studyline;
use local_treestudyplan\studyplan;

/**
 * Privacy provider.
 * (Note: Interfaces are in reverse alphabetical order, since there seems to be a bug in
 *        the php codestyle checker that *should* expect them to be forward alphabetical order.)
 */
class provider implements
    \core_privacy\local\metadata\provider,
    \core_privacy\local\request\core_userlist_provider,
    \core_privacy\local\request\plugin\provider
{
    /**
     * Get the language string identifier with the component's language
     * file to explain why this plugin stores no data.
     *
     * @return  string
     */
    public static function get_reason(): string {
        return 'privacy:metadata';
    }

    /**
     * Get metadata about collected personal data
     * @param collection $collection
     * @return collection
     */
    public static function get_metadata(collection $collection): collection {

        $collection->add_database_table(
            'local_treestudyplan_invit',
            [
                'user_id' => 'privacy:metadata:invit:user_id',
                'name' => 'privacy:metadata:invit:name',
                'email' => 'privacy:metadata:invit:email',
                'idate' => 'privacy:metadata:invit:date',
                'unlockdate' => 'privacy:metadata:invit:unlockdate',
                'identifier' => 'privacy:metadata:invit:identifier',
            ],
            'privacy:metadata:invit'
        );
        $collection->add_database_table(
            'local_treestudyplan_user',
            [
                'user_id' => 'privacy:metadata:user:user_id',
                'studyplan_id' => 'privacy:metadata:user:studyplan_id',
            ],
            'privacy:metadata:user'
        );
        $collection->add_database_table(
            'local_treestudyplan_teachers',
            [
                'teacher_id' => 'privacy:metadata:teachers:teacher_id',
                'studyplan_id' => 'privacy:metadata:teachers:studyplan_id',
            ],
            'privacy:metadata:teachers'
        );
        $collection->add_database_table(
            'local_treestudyplan_lineuser',
            [
                'user_id' => 'privacy:metadata:lineuser:user_id',
                'line_id' => 'privacy:metadata:lineuser:line_id',
                'timeenrolled' => 'privacy:metadata:lineuser:timeenrolled',
                'enrolled' => 'privacy:metadata:lineuser:enrolledby',
                'enrolledby' => 'privacy:metadata:lineuser:enrolledby',
            ],
            'privacy:metadata:lineuser'
        );
        $collection->add_database_table(
            'local_treestudyplan_coach',
            [
                'user_id' => 'privacy:metadata:coach:user_id',
                'studyplan_id' => 'privacy:metadata:coach:studyplan_id',
            ],
            'privacy:metadata:coach'
        );
        return $collection;
    }

    /**
     * Get the list of contexts that contain user information for the specified user.
     * @param   int         $userid     The user to search.
     * @return  contextlist   $contextlist  The contextlist containing the list of contexts used in this plugin.
     */
    public static function get_contexts_for_userid(int $userid): contextlist {
        $contextlist = new \core_privacy\local\request\contextlist();
        $contextlist->add_system_context(); // For invitations.

        // Add contexts for linked studyplans.
        $sql = "SELECT s.context_id FROM {local_treestudyplan} s
                    INNER JOIN {local_treestudyplan_user} a ON a.studyplan_id = s.id
                WHERE ( a.user_id = :userid )";
        $contextlist->add_from_sql($sql, ['userid'  => $userid]);

        // Add contexts for coaching studyplans.
        $sql = "SELECT s.context_id FROM {local_treestudyplan} s
                    INNER JOIN {local_treestudyplan_coach} a ON a.studyplan_id = s.id
                WHERE ( a.user_id = :userid )";
        $contextlist->add_from_sql($sql, ['userid'  => $userid]);

        // Add contexts for teaching studyplans.
        $sql = "SELECT s.context_id FROM {local_treestudyplan} s
                    INNER JOIN {local_treestudyplan_teachers} a ON a.studyplan_id = s.id
                WHERE ( a.teacher_id = :userid )";
        $contextlist->add_from_sql($sql, ['userid'  => $userid]);

        $sql = "SELECT s.context_id FROM {local_treestudyplan} s
                INNER JOIN {local_treestudyplan_page} p ON p.studyplan_id = s.id
                INNER JOIN {local_treestudyplan_line} l ON l.page_id = p.id
                INNER JOIN {local_treestudyplan_lineuser} e ON e.line_id = l.id
                WHERE (e.user_id = :userid OR e.enrolledby = :euserid)";
         $contextlist->add_from_sql($sql, ['userid'  => $userid, 'euserid'  => $userid]);

        return $contextlist;
    }

    /**
     * Export all user data for the specified user, in the specified contexts.
     * @param   approved_contextlist    $contextlist    The approved contexts to export information for.
     */
    public static function export_user_data(approved_contextlist $contextlist) {
        global $DB;

        foreach ($contextlist->get_contexts() as $context) {
            $user = $contextlist->get_user();

            if ($context->contextlevel == CONTEXT_SYSTEM) {
                // Export invitations.
                $sql = "SELECT * FROM {local_treestudyplan_invit} i
                        WHERE ( i.user_id = :userid )
                ";
                $records = $DB->get_records_sql($sql, ["userid" => $user->id]);
                foreach ($records as $r) {
                    static::export_invitation_data_for_user($r, $context);
                }

                // Export studyplan student associations.
                $sql = "SELECT s.id as id FROM {local_treestudyplan} s
                        INNER JOIN {local_treestudyplan_user} a ON a.studyplan_id = s.id
                        WHERE a.user_id = :userid AND (s.context_id IS NULL or s.context_id <= 1)";
                $ids = $DB->get_fieldset_sql($sql, ["userid" => $user->id]);
                foreach ($ids as $id) {
                    $plan = studyplan::find_by_id($id);
                    static::export_studyplan_data_for_user($plan, $context, "Student (directly linked)");
                }

                // Export studyplan coaching associations.
                $sql = "SELECT s.id FROM {local_treestudyplan} s
                        INNER JOIN {local_treestudyplan_coach} a ON a.studyplan_id = s.id
                        WHERE a.user_id = :userid AND (s.context_id IS NULL or s.context_id <= 1)";
                $ids = $DB->get_fieldset_sql($sql, ["userid" => $user->id]);
                foreach ($ids as $id) {
                    $plan = studyplan::find_by_id($id);
                    static::export_studyplan_data_for_user($plan, $context, "Coach");
                }

                // Export studyplan teaching associations.
                $sql = "SELECT s.id FROM {local_treestudyplan} s
                        INNER JOIN {local_treestudyplan_teachers} a ON a.studyplan_id = s.id
                        WHERE a.teacher_id = :userid AND (s.context_id IS NULL or s.context_id <= 1)";
                $ids = $DB->get_fieldset_sql($sql, ["userid" => $user->id]);
                foreach ($ids as $id) {
                    $plan = studyplan::find_by_id($id);
                    static::export_studyplan_data_for_user($plan, $context, "Teaching");
                }

                // Export studyline enrolled associations.
                $sql = "SELECT e.* FROM {local_treestudyplan_lineuser} e
                        INNER JOIN {local_treestudyplan_line} l ON e.line_id = l.id
                        INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                        INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                        WHERE (e.user_id = :userid OR e.enrolledby = :euserid)
                            AND (s.context_id IS NULL or s.context_id <= 1)
                ";
                $records = $DB->get_records_sql($sql, ["userid" => $user->id, "euserid" => $user->id]);
                foreach ($records as $r) {
                    if ($r->user_id == $user->id) {
                        static::export_line_enrolment_data_for_user($r, $context, "Enrolled in a line");
                    }
                    if ($r->enrolledby == $user->id) {
                        static::export_line_enrolment_data_for_user($r, $context, "Enrolled another user in a line");
                    }
                }
            } else if ($context->contextlevel == CONTEXT_COURSECAT) {
                // Export studyplan student associations.
                $sql = "SELECT s.id FROM {local_treestudyplan} s
                        INNER JOIN {local_treestudyplan_user} a ON a.studyplan_id = s.id
                        WHERE ( a.user_id = :userid AND s.context_id = :contextid)";
                $ids = $DB->get_fieldset_sql($sql, ["userid" => $user->id, "contextid" => $context->id]);
                foreach ($ids as $id) {
                    $plan = studyplan::find_by_id($id);
                    static::export_studyplan_data_for_user($plan, $context, "Student (directly linked)");
                }

                // Export studyplan coaching associations.
                $sql = "SELECT s.id FROM {local_treestudyplan} s
                        INNER JOIN {local_treestudyplan_coach} a ON a.studyplan_id = s.id
                        WHERE ( a.user_id = :userid AND s.context_id = :contextid)";
                $ids = $DB->get_fieldset_sql($sql, ["userid" => $user->id, "contextid" => $context->id]);
                foreach ($ids as $id) {
                    $plan = studyplan::find_by_id($id);
                    static::export_studyplan_data_for_user($plan, $context, "Coach");
                }

                // Export studyplan teaching associations.
                $sql = "SELECT s.id FROM {local_treestudyplan} s
                        INNER JOIN {local_treestudyplan_teachers} a ON a.studyplan_id = s.id
                        WHERE ( a.teacher_id = :userid AND s.context_id = :contextid)";
                $ids = $DB->get_fieldset_sql($sql, ["userid" => $user->id, "contextid" => $context->id]);
                foreach ($ids as $id) {
                    $plan = studyplan::find_by_id($id);
                    static::export_studyplan_data_for_user($plan, $context, "Teaching");
                }

                // Export studyline enrolled associations.
                $sql = "SELECT e.* FROM {local_treestudyplan_lineuser} e
                INNER JOIN {local_treestudyplan_line} l ON e.line_id = l.id
                INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                WHERE (e.user_id = :userid OR e.enrolledby = :euserid)
                        AND (s.context_id = :contextid)
                ";
                $records = $DB->get_records_sql($sql, ["userid" => $user->id, "euserid" => $user->id, "contextid" => $context->id]);
                foreach ($records as $r) {
                    if ($r->user_id == $user->id) {
                        static::export_line_enrolment_data_for_user($r, $context, "Enrolled in a studyplan line");
                    }
                    if ($r->enrolledby == $user->id) {
                        static::export_line_enrolment_data_for_user($r, $context, "Enrolled another user in a studyplan line");
                    }
                }
            }
        }
    }

    /**
     * Export the supplied personal data for an invitation.
     * @param stdClass $invit The invitation record.
     * @param context $context The relevant  context.
     */
    protected static function export_invitation_data_for_user($invit, context $context) {
        $subcontext = ["Studyplan", "Invitations"];
        $data = new \stdClass();
        $data->recipient = $invit->name;
        $data->email = $invit->email;
        writer::with_context($context)->export_data($subcontext, $data);
    }

    /**
     * Export studyplan data for (current) user
     * @param studyplan $studyplan The studyplan
     * @param context $context The relevant  context.
     * @param string $subcontext Name of the main subcontext type
     */
    protected static function export_studyplan_data_for_user(studyplan $studyplan, $context, $subcontext) {
        $data = new \stdClass();
        $data->fullname = $studyplan->name();
        $data->shortname = $studyplan->shortname();
        $data->idnumber = $studyplan->idnumber();
        $data->context = (new contextinfo($context))->path();

        $path = ($context->contextlevel == CONTEXT_SYSTEM) ? [] : (new contextinfo($context))->path();
        $subcontextpath = array_merge(["Studyplan", $subcontext], $path, [$studyplan->name()]);
        writer::with_context(context_system::instance())->export_data($subcontextpath, $data);
    }

    /**
     * Export the supplied personal data for a study line enrollment.
     * @param stdClass $enrol The enrolment record.
     * @param context $context The relevant context.
     * @param string $subcontext Name of the main subcontext type
     */
    protected static function export_line_enrolment_data_for_user($enrol, $context, $subcontext) {
        $data = new \stdClass();
        $line = studyline::find_by_id($enrol->line_id);
        $studyplan = $line->studyplan();
        $page = $line->page();
        $data->studyplan = $studyplan->name();
        $data->page = $page->fullname();
        $data->line = $line->name();
        $data->enrolled = ($enrol->enrolled) ? "True" : "False";
        $data->enrolledsince = (new \DateTime($enrol->timeenrolled))->format("X-m-d\\TH:i:sP");

        $path = ($context->contextlevel == CONTEXT_SYSTEM) ? [] : (new contextinfo($context))->path();
        $subcontextpath = array_merge(["Studyplan", $subcontext], $path, [$studyplan->name()]);
        writer::with_context(context_system::instance())->export_data($subcontextpath, $data);
    }

    /**
     * Delete all data for all users in the specified context.
     * Used when a context is past it's data retention period
     * @param context $context   The specific context to delete data for.
     */
    public static function delete_data_for_all_users_in_context($context) {
        global $DB;
        // Find studyplans in context.
        if ($context->contextlevel == CONTEXT_COURSECAT) {
            $sql = "SELECT s.id FROM {local_treestudyplan} s WHERE (s.context_id = :contextid)";
            $planids = $DB->get_fieldset_sql($sql, ["contextid" => $context->id]);

            // Remove all associated users to the studyplan.
            foreach ($planids as $planid) {
                $DB->delete_records("local_treestudyplan_user", ["studyplan_id" => $planid]);
                $DB->delete_records("local_treestudyplan_cohort", ["studyplan_id" => $planid]);
                $DB->delete_records("local_treestudyplan_teachers", ["studyplan_id" => $planid]);
                $DB->delete_records("local_treestudyplan_coach", ["studyplan_id" => $planid]);
            }

            // Remove all line enrolment associations.
            $sql = "SELECT l.id FROM {local_treestudyplan_line} l
                    INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                    INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                    WHERE (s.context_id = :contextid)";
            $lineids = $DB->get_fieldset_sql($sql, ["contextid" => $context->id]);
            foreach ($lineids as $lineid) {
                $DB->delete_records("local_treestudyplan_lineuser", ["line_id" => $lineid]);
            }
        }
    }

    /**
     * Removes all user data for one user in one specific context
     * @param context $context The context in which to remove the user
     * @param int $userid The userid of the user to remove
     */
    public static function delete_userdata_in_context(context $context, int $userid) {
        global $DB;
        if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
            if ($context->contextlevel == CONTEXT_SYSTEM) {
                // Also delete all invitations for this user.
                $DB->delete_records("local_treestudyplan_invit", ["user_id" => $userid]);

                // Retrieve all studyplans in system context.
                $sql = "SELECT s.id FROM {local_treestudyplan} s INNER JOIN {local_treestudyplan_user} a ON a.studyplan_id = s.id
                        WHERE (s.context_id <= 1)";
                $planids = $DB->get_fieldset_sql($sql);

                // Find all lineids in system context.
                $sql = "SELECT l.id FROM {local_treestudyplan_line} l
                    INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                    INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                    WHERE (s.context_id <= 1)";
                $lineids = $DB->get_fieldset_sql($sql);
            } else { // Context level is CONTEXT_COURSECAT.
                // Retrieve all studyplans in this category.
                $sql = "SELECT s.id FROM {local_treestudyplan} s INNER JOIN {local_treestudyplan_user} a ON a.studyplan_id = s.id
                        WHERE (s.context_id = :contextid)";
                $planids = $DB->get_fieldset_sql($sql, ["contextid" => $context->id]);

                // Find all lineids in this context.
                $sql = "SELECT l.id FROM {local_treestudyplan_line} l
                    INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                    INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                    WHERE (s.context_id = :contextid)";
                $lineids = $DB->get_fieldset_sql($sql, ["contextid" => $context->id]);
            }

            foreach ($planids as $planid) {
                // Remove all associated users to the studyplan.
                $DB->delete_records("local_treestudyplan_user", ["studyplan_id" => $planid, "user_id" => $userid]);
                $DB->delete_records("local_treestudyplan_teachers", ["studyplan_id" => $planid, "teacher_id" => $userid]);
                $DB->delete_records("local_treestudyplan_coach", ["studyplan_id" => $planid, "user_id" => $userid]);
            }
            foreach ($lineids as $lineid) {
                // Remove all line enrollments for this user.
                $DB->delete_records("local_treestudyplan_lineuser", ["line_id" => $lineid, "user_id" => $userid]);

                // Replace all enrolledby references with the admin user (2).
                $records = $DB->get_records("local_treestudyplan_lineuser", ["line_id" => $lineid, "enrolledby" => $userid]);
                foreach ($records as $r) {
                    $r->enrolledby = 2; // Replace by admin user.
                    $DB->update_record("local_treestudyplan_lineuser", $r);
                }
            }
        }
    }


    /**
     * Delete all user data for the specified user, in the specified contexts.
     *
     * @param   approved_contextlist    $contextlist    The approved contexts and user information to delete information for.
     */
    public static function delete_data_for_user(approved_contextlist $contextlist) {
        $user = $contextlist->get_user();

        foreach ($contextlist->get_contexts() as $context) {
            static::delete_userdata_in_context($context, $user->id);
        }
    }

    /**
     * Get the list of users who have data within a context.
     * @param   userlist    $userlist   The userlist containing the list of users who have data in this context/plugin combination.
     */
    public static function get_users_in_context(userlist $userlist) {
        global $DB;
        $context = $userlist->get_context();

        // Studyplan contexts are only System and Categories.
        if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
            if ($context->contextlevel == CONTEXT_SYSTEM) {
                // Add all invitations.
                $sql = "SELECT i.user_id as userid
                        FROM {local_treestudyplan_invit} i";
                $userlist->add_from_sql('userid', $sql, []);

                // Add directly associated users.
                $sql = "SELECT a.user_id as userid FROM {local_treestudyplan_user} a
                        INNER JOIN {local_treestudyplan} s ON a.studyplan_id = s.id
                        WHERE ( s.context_id is NULL or s.context_id <= 1)";
                $userlist->add_from_sql('userid', $sql, []);

                // Add coaching users.
                $sql = "SELECT a.user_id as userid FROM {local_treestudyplan_coach} a
                        INNER JOIN {local_treestudyplan} s ON a.studyplan_id = s.id
                        WHERE ( s.context_id is NULL or s.context_id <= 1)";
                $userlist->add_from_sql('userid', $sql, []);

                // Do not add teaching users, since this is simply a cache of data elsewhere in the system.

                // Find all lineids in this context to process in next step.
                $sql = "SELECT l.id FROM {local_treestudyplan_line} l
                        INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                        INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                        WHERE (sa.context_id is NULL or a.context_id <= 1)";
                $lineids = $DB->get_fieldset_sql($sql, []);
            } else {
                // Add directly associated users.
                $sql = "SELECT a.user_id as userid FROM {local_treestudyplan_user} a
                        INNER JOIN {local_treestudyplan} s ON a.studyplan_id = s.id
                        WHERE ( s.context_id = :contextid )";
                $userlist->add_from_sql('userid', $sql, ["contextid" => $context->id]);

                // Add coaching users.
                $sql = "SELECT a.user_id as userid FROM {local_treestudyplan_coach} a
                        INNER JOIN {local_treestudyplan} s ON a.studyplan_id = s.id
                        WHERE ( s.context_id = :contextid )";
                $userlist->add_from_sql('userid', $sql, ["contextid" => $context->id]);

                // Do not add teaching users, since this is simply a cache of data elsewhere in the system.

                // Find all lineids in this context to process in next step.
                $sql = "SELECT l.id FROM {local_treestudyplan_line} l
                        INNER JOIN {local_treestudyplan_page} p ON l.page_id = p.id
                        INNER JOIN {local_treestudyplan} s ON p.studyplan_id = s.id
                        WHERE (s.context_id = :contextid)";
                $lineids = $DB->get_fieldset_sql($sql, ["contextid" => $context->id]);
            }

            foreach ($lineids as $lineid) {
                // List directly enrolled users.
                $sql = "SELECT e.user_id as userid FROM {local_treestudyplan_lineuser} e
                        WHERE ( e.line_id = :lineid )";
                $userlist->add_from_sql('userid', $sql, ["lineid" => $lineid]);

                // And list enrolledby users.
                $sql = "SELECT e.enrolledby as userid FROM {local_treestudyplan_lineuser} e
                        WHERE ( e.line_id = :lineid AND e.enrolledby IS NOT NULL)";
                $userlist->add_from_sql('userid', $sql, ["lineid" => $lineid]);
            }
        }
    }

    /**
     * Delete multiple users within a single context.
     * @param   approved_userlist       $userlist The approved context and user information to delete information for.
     */
    public static function delete_data_for_users(approved_userlist $userlist) {
        $context = $userlist->get_context();
        $users = $userlist->get_userids();

        foreach ($users as $userid) {
            static::delete_userdata_in_context($context, $userid);
        }
    }
}
