<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;

final class ScheduleCopyService
{
    public static function copyGroupSchedule(int $sourceGroupId, int $targetGroupId): array
    {
        $db = App::getInstance()->db();

        $source = $db->selectOne(
            "SELECT id, name_ar FROM sa_groups WHERE id = ? AND is_archived = 0",
            [$sourceGroupId]
        );
        if (!$source) {
            return ['success' => false, 'error' => 'المجموعة المصدر غير موجودة'];
        }

        $target = $db->selectOne(
            "SELECT id, name_ar FROM sa_groups WHERE id = ? AND is_archived = 0",
            [$targetGroupId]
        );
        if (!$target) {
            return ['success' => false, 'error' => 'المجموعة المستهدفة غير موجودة'];
        }

        $schedules = $db->select(
            "SELECT * FROM sa_group_schedule WHERE group_id = ? AND is_active = 1",
            [$sourceGroupId]
        );

        if (empty($schedules)) {
            return ['success' => false, 'error' => 'المجموعة المصدر ليس لها جدول'];
        }

        $db->beginTransaction();
        try {
            $db->query(
                "UPDATE sa_group_schedule SET is_active = 0, updated_at = NOW() WHERE group_id = ?",
                [$targetGroupId]
            );

            $copied = 0;
            $now = date('Y-m-d H:i:s');
            foreach ($schedules as $sch) {
                $db->insert('sa_group_schedule', [
                    'group_id'         => $targetGroupId,
                    'facility_unit_id' => (int) $sch['facility_unit_id'],
                    'day_of_week'      => (int) $sch['day_of_week'],
                    'start_time'       => $sch['start_time'],
                    'end_time'         => $sch['end_time'],
                    'is_active'        => 1,
                    'created_at'       => $now,
                    'updated_at'       => $now,
                ]);
                $copied++;
            }

            $db->commit();
            return ['success' => true, 'copied' => $copied];
        } catch (\Throwable $e) {
            $db->rollBack();
            return ['success' => false, 'error' => 'فشل نسخ الجدول: ' . $e->getMessage()];
        }
    }

    public static function copyProgramScheduleToAllGroups(int $programId): array
    {
        $db = App::getInstance()->db();

        $groups = $db->select(
            "SELECT id FROM sa_groups WHERE program_id = ? AND status = 'active' AND is_archived = 0",
            [$programId]
        );

        if (count($groups) < 2) {
            return ['success' => false, 'error' => 'يجب وجود مجموعتين على الأقل في البرنامج'];
        }

        $templateGroup = $db->selectOne(
            "SELECT g.id FROM sa_groups g
             INNER JOIN sa_group_schedule gs ON gs.group_id = g.id AND gs.is_active = 1
             WHERE g.program_id = ? AND g.status = 'active' AND g.is_archived = 0
             GROUP BY g.id
             ORDER BY COUNT(gs.id) DESC
             LIMIT 1",
            [$programId]
        );

        if (!$templateGroup) {
            return ['success' => false, 'error' => 'لا توجد مجموعة بها جدول يمكن نسخه'];
        }

        $sourceId = (int) $templateGroup['id'];
        $totalCopied = 0;
        $errors = [];

        foreach ($groups as $g) {
            if ((int) $g['id'] === $sourceId) {
                continue;
            }

            $result = self::copyGroupSchedule($sourceId, (int) $g['id']);
            if ($result['success']) {
                $totalCopied += $result['copied'];
            } else {
                $errors[] = "مجموعة #{$g['id']}: {$result['error']}";
            }
        }

        return [
            'success'       => true,
            'source_id'     => $sourceId,
            'total_copied'  => $totalCopied,
            'groups_updated' => count($groups) - 1,
            'errors'        => $errors,
        ];
    }

    public static function shiftScheduleTime(int $groupId, int $minutesDelta): array
    {
        $db = App::getInstance()->db();

        $schedules = $db->select(
            "SELECT id, start_time, end_time FROM sa_group_schedule WHERE group_id = ? AND is_active = 1",
            [$groupId]
        );

        if (empty($schedules)) {
            return ['success' => false, 'error' => 'لا يوجد جدول لهذه المجموعة'];
        }

        $db->beginTransaction();
        try {
            foreach ($schedules as $sch) {
                $newStart = date('H:i:s', strtotime($sch['start_time']) + ($minutesDelta * 60));
                $newEnd = date('H:i:s', strtotime($sch['end_time']) + ($minutesDelta * 60));

                $db->update('sa_group_schedule', [
                    'start_time' => $newStart,
                    'end_time'   => $newEnd,
                    'updated_at' => date('Y-m-d H:i:s'),
                ], 'id = ?', [(int) $sch['id']]);
            }

            $db->commit();
            return ['success' => true, 'shifted' => count($schedules), 'delta_minutes' => $minutesDelta];
        } catch (\Throwable $e) {
            $db->rollBack();
            return ['success' => false, 'error' => 'فشل تعديل المواعيد: ' . $e->getMessage()];
        }
    }
}
