<?php

namespace App\Support;

use App\Models\ActivityLog;
use App\Models\ProjectModule;
use App\Models\ProjectTask;
use App\Models\ProjectTaskParticipant;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class TaskExpiryHelper
{
    /**
     * Clean up tasks that were submitted for review but not approved on that day.
     * These tasks automatically reset/disappear the next day.
     */
    public static function cleanupExpiredTasks(): void
    {
        $today = Carbon::today(config('app.timezone'));

        // Fetch tasks in 'review' status submitted before today
        $expiredTasks = ProjectTask::where('status', 'review')
            ->whereNotNull('tanggal_selesai_kerja')
            ->where('tanggal_selesai_kerja', '<', $today)
            ->get();

        if ($expiredTasks->isEmpty()) {
            return;
        }

        foreach ($expiredTasks as $task) {
            DB::transaction(function () use ($task) {
                // Delete participants
                ProjectTaskParticipant::where('task_id', $task->id)->delete();

                // Get submission IDs
                $submissionIds = DB::table('md_work_submissions')
                    ->where('task_id', $task->id)
                    ->pluck('id');

                // Delete related replies
                DB::table('md_project_note_replies')
                    ->where('task_id', $task->id)
                    ->when($submissionIds->isNotEmpty(), function ($query) use ($submissionIds) {
                        return $query->orWhereIn('submission_id', $submissionIds);
                    })
                    ->delete();

                // Delete work submissions
                DB::table('md_work_submissions')
                    ->where('task_id', $task->id)
                    ->delete();

                $isModuleTask = str_starts_with((string) $task->judul, ProjectTask::MODULE_ASSIGNMENT_PREFIX);
                $moduleId = $task->module_id;
                $taskTitle = $task->judul;
                $projectId = $task->project_id;

                if ($isModuleTask) {
                    $task->delete();
                    if ($moduleId) {
                        $module = ProjectModule::find($moduleId);
                        $module?->recalculateProgress();
                    }
                } else {
                    $task->update([
                        'user_id' => null,
                        'status' => 'belum_dikerjakan',
                        'catatan_revisi' => null,
                        'laporan_kerja' => null,
                        'file_lampiran' => null,
                        'tanggal_selesai_kerja' => null,
                    ]);
                    $task->recalculateModuleProgress();
                }

                // Log the system-level cleanup activity
                ActivityLog::create([
                    'user_id' => null,
                    'project_id' => $projectId,
                    'aktivitas' => 'Sistem membatalkan pengerjaan tugas "' . $taskTitle . '" karena tidak disetujui pada hari penyerahan.',
                ]);
            });
        }
    }
}
