<?php
    /*
                *****************************************************************************
                * MEGA Digital Space - by MEGA Digital Studio                               *
                * ------------------------------------------------------------------------- *
                * CMS Website:  https://megadigital.space                                   *
                * License:  https://megadigital.space/license                               *
                * Owner:  Giorgi Basharuli                                                  *
                * Contact:  online@megadigital.studio                                       *
                * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
                * Website:  https://megadigital.studio                                      *
                * ------------------------------------------------------------------------- *
                * Description: This file is a part of the MEGA Digital Space CMS system.    *
                * Unauthorized distribution, modification, or commercial use is strictly -  *
                * prohibited without prior written permission.                              *
                * ------------------------------------------------------------------------- *
                * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
                * All rights reserved.                                                      *
                *****************************************************************************
            */

    function teacherStudentProgressController()
    {
        global $db_connect, $smarty;

        $teacherId = (int)$_SESSION['user_id'];

        // Ученики учителя
        $classIds = $db_connect->select("teacher_classes", "class_id", [
            "teacher_id" => $teacherId
        ]);

        $students = [];
        if (!empty($classIds)) {
            $students = $db_connect->select("class_students", [
                "[>]users" => ["student_id" => "id"]
            ], [
                "users.id",
                "users.name"
            ], [
                "class_students.class_id" => $classIds
            ]);
        }

        // Категории
        $categories = $db_connect->select("progress_categories", "*");

        // Активности
        $activityList = $db_connect->select("student_progress", [
            "[>]users" => ["student_id" => "id"],
            "[>]progress_categories" => ["category_id" => "id"]
        ], [
            "student_progress.id",
            "student_progress.progress_level",
            "student_progress.summary",
            "student_progress.created_at",
            "users.name(student_name)",
            "progress_categories.title(category_title)"
        ], [
            "student_progress.teacher_id" => $teacherId,
            "ORDER" => ["student_progress.created_at" => "DESC"]
        ]);

        $smarty->assign([
            "activityList"   => $activityList,
            "studentOptions" => $students,
            "categoryOptions"=> $categories
        ]);
    }

    function parentStudentProgressController()
    {
        global $db_connect, $smarty;

        $parentId = (int)$_SESSION['user_id'];

        // 1. Все дети родителя
        $children = $db_connect->select("parents_students", [
            "[>]users" => ["student_id" => "id"]
        ], [
            "users.id",
            "users.name"
        ], [
            "parents_students.parent_id" => $parentId
        ]);

        if (empty($children)) {
            die('NO_CHILDREN');
        }

        // 2. Выбранный ребёнок
        $studentId = (int)($_GET['student_id'] ?? $children[0]['id']);

        // защита: проверка принадлежности
        $allowedIds = array_column($children, 'id');
        if (!in_array($studentId, $allowedIds, true)) {
            die('ACCESS_DENIED');
        }

        // 3. Прогресс (агрегация по категориям)
        $rows = $db_connect->select("student_progress", [
            "[>]users(student)" => ["student_id" => "id"],      // ученик
            "[>]users(teacher)" => ["teacher_id" => "id"],     // учитель
            "[>]progress_categories" => ["category_id" => "id"]
        ], [
            "student_progress.id",
            "student_progress.progress_level",
            "student_progress.summary",
            "student_progress.created_at",
            "student.name(student_name)",
            "student.avatar(student_avatar)",
            "teacher.name(teacher_name)",                       // имя учителя
            "progress_categories.id(category_id)",
            "progress_categories.title(category_title)"
        ], [
            //"student_progress.student_id" => $studentId,
            "ORDER" => ["student_progress.created_at" => "DESC"]
        ]);

        $labelMap = [
            2  => ["label" => "Отличный прогресс", "color" => "success"],
            1  => ["label" => "Есть улучшения",    "color" => "success"],
            0  => ["label" => "Без изменений",     "color" => "secondary"],
            -1 => ["label" => "Нужна помощь",      "color" => "warning"],
            -2 => ["label" => "Есть сложности",    "color" => "danger"],
        ];

        $progressByCategory = [];

        foreach ($rows as $row) {
            $status = $labelMap[$row['progress_level']] ?? $labelMap[0];

            // snapshots
            $snaps = $db_connect->select("progress_snapshots", "*", [
                "progress_id" => $row['id']
            ]);

            $before = '';
            $after  = '';
            $media  = [];

            foreach ($snaps as $s) {
                $entries = $db_connect->select("progress_entries", "*", [
                    "snapshot_id" => $s['id'],
                    "ORDER" => ["position" => "ASC"]
                ]);

                foreach ($entries as $e) {
                    if ($e['type'] === 'text') {
                        $txt = $db_connect->get("progress_texts", "content", [
                            "entry_id" => $e['id']
                        ]);
                        if ($s['stage'] === 'before') $before = $txt;
                        if ($s['stage'] === 'after')  $after  = $txt;
                    } else {
                        $media[] = $db_connect->get("progress_media", "*", [
                            "entry_id" => $e['id']
                        ]);
                    }
                }
            }

            $cid = $row['category_id'];
            $progressByCategory[$cid]['title'] = $row['category_title'];
            $progressByCategory[$cid]['items'][] = [
                "date"        => $row['created_at'],
                "label"       => $status['label'],
                "color"       => $status['color'],
                "summary"     => $row['summary'],
                "before_text" => $before,
                "after_text"  => $after,
                "media"       => $media,
                "student_name" => $row["student_name"],
                "student_avatar" => $row["student_avatar"],
                "teacher_name" => $row["teacher_name"]
            ];
        }

        $smarty->assign([
            "children" => $children,
            "activeStudentId" => $studentId,
            "progressByCategory" => $progressByCategory
        ]);
    }

    function saveStudProgressController()
    {
        global $db_connect;

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        $teacherId  = (int)$_SESSION['user_id'];
        $studentId  = (int)($_POST['student_id'] ?? 0);
        $categoryId = (int)($_POST['category_id'] ?? 0);
        $level      = (int)($_POST['progress_level'] ?? 0);
        $summary    = trim($_POST['summary'] ?? '');

        if (!$studentId || !$categoryId) {
            die('INVALID_INPUT');
        }

        try {
            $db_connect->pdo->beginTransaction();

            /** 1. progress */
            $db_connect->insert("student_progress", [
                "student_id"     => $studentId,
                "teacher_id"     => $teacherId,
                "category_id"    => $categoryId,
                "progress_level" => $level,
                "summary"        => $summary
            ]);

            $progressId = $db_connect->id();

            /** 2. snapshots */
            $snapshots = [];
            foreach (['before', 'after'] as $stage) {
                $db_connect->insert("progress_snapshots", [
                    "progress_id" => $progressId,
                    "stage"       => $stage
                ]);
                $snapshots[$stage] = $db_connect->id();
            }

            /** 3. texts */
            $texts = $_POST['texts'] ?? [];
            foreach (['before','after'] as $stage) {
                if (empty(trim($texts[$stage] ?? ''))) continue;

                $db_connect->insert("progress_entries", [
                    "snapshot_id" => $snapshots[$stage],
                    "progress_id" => $progressId,
                    "type"        => "text",
                    "position"    => 1
                ]);

                $entryId = $db_connect->id();

                $db_connect->insert("progress_texts", [
                    "entry_id" => $entryId,
                    "content"  => trim($texts[$stage])
                ]);
            }

            /** 4. media */
            $media = $_FILES['media'] ?? [];
            foreach (['before','after'] as $stage) {

                if (empty($media['name'][$stage])) continue;

                $pos = 2;

                foreach ($media['name'][$stage] as $i => $name) {
                    if (!$name) continue;

                    $tmp  = $media['tmp_name'][$stage][$i];
                    $type = $media['type'][$stage][$i];
                    $size = $media['size'][$stage][$i];

                    $ext = pathinfo($name, PATHINFO_EXTENSION);
                    $fileName = uniqid('prog_', true) . '.' . $ext;
                    $path = "/uploads/progress/" . $fileName;

                    move_uploaded_file($tmp, $_SERVER['DOCUMENT_ROOT'] . $path);

                    $db_connect->insert("progress_entries", [
                        "snapshot_id" => $snapshots[$stage],
                        "progress_id" => $progressId,
                        "type"        => str_starts_with($type, 'video') ? 'video' : 'image',
                        "position"    => $pos++
                    ]);

                    $entryId = $db_connect->id();

                    $db_connect->insert("progress_media", [
                        "entry_id"     => $entryId,
                        "file_path"    => $path,
                        "mime_type"    => $type,
                        "size_kb"      => round($size / 1024),
                        "duration_sec" => null
                    ]);
                }
            }

            $db_connect->pdo->commit();

            header("Location: ".$_SERVER['HTTP_REFERER']);
            exit;

        } catch (Throwable $e) {
            $db_connect->pdo->rollBack();
            die("ERROR: ".$e->getMessage());
        }
    }

