<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class ReportController extends Controller
{
    /**
     * Show user report with filters.
     */
    public function userReport(Request $request)
    {
        $users = $this->buildUserReportQuery($request)->get();
        return view('admin.reports.user_report', compact('users'));
    }

    public function userReportPdf(Request $request)
    {
        $users = $this->buildUserReportQuery($request)->get();

        $pdf = Pdf::loadView('admin.reports.pdf.user_report_pdf', compact('users'));
        return $pdf->download('user-report-' . now()->format('Ymd_His') . '.pdf');
    }

    public function index()
    {
        $workflows = \App\Models\Workflow::with('createdBy')->latest()->get();
        $tasks = \App\Models\WorkflowTask::with(['assignedUser', 'assignedRole', 'instance'])->latest()->get();
        $users = \App\Models\User::latest()->get();
        $folders = \App\Models\Folder::latest()->get();
        return view('admin.reports.index', compact('workflows', 'tasks', 'users', 'folders'));
    }

    /**
     * Show folder and file statistics report.
     */
    public function folderFileStats(Request $request)
    {
        $folders = $this->buildFolderStatsQuery($request)->get();

        $filesByFolder = \App\Models\FileMetadata::select('folder_id')
            ->selectRaw('COUNT(*) as file_count')
            ->groupBy('folder_id')
            ->pluck('file_count', 'folder_id');

        $totalFiles = \App\Models\FileMetadata::count();
        $totalFolders = \App\Models\Folder::count();

        return view('admin.reports.folder_file_stats', compact('folders', 'filesByFolder', 'totalFiles', 'totalFolders'));
    }

    public function folderFileStatsPdf(Request $request)
    {
        $folders = $this->buildFolderStatsQuery($request)->get();

        $filesByFolder = \App\Models\FileMetadata::select('folder_id')
            ->selectRaw('COUNT(*) as file_count')
            ->groupBy('folder_id')
            ->pluck('file_count', 'folder_id');

        $totalFiles = \App\Models\FileMetadata::count();
        $totalFolders = \App\Models\Folder::count();

        $pdf = Pdf::loadView('admin.reports.pdf.folder_file_stats_pdf', compact('folders', 'filesByFolder', 'totalFiles', 'totalFolders'))
            ->setPaper('a4', 'landscape');

        return $pdf->download('folder-file-stats-' . now()->format('Ymd_His') . '.pdf');
    }

    public function workflowReport(Request $request)
    {
        $workflows = $this->buildWorkflowReportQuery($request)->latest()->get();
        return view('admin.reports.workflow_report', compact('workflows'));
    }

    public function workflowReportPdf(Request $request)
    {
        $workflows = $this->buildWorkflowReportQuery($request)->latest()->get();

        $pdf = Pdf::loadView('admin.reports.pdf.workflow_report_pdf', compact('workflows'));
        return $pdf->download('workflow-report-' . now()->format('Ymd_His') . '.pdf');
    }

    public function taskReport(Request $request)
    {
        $tasks = $this->buildTaskReportQuery($request)->latest()->get();
        return view('admin.reports.task_report', compact('tasks'));
    }

    public function taskReportPdf(Request $request)
    {
        $tasks = $this->buildTaskReportQuery($request)->latest()->get();

        $pdf = Pdf::loadView('admin.reports.pdf.task_report_pdf', compact('tasks'))
            ->setPaper('a4', 'landscape');

        return $pdf->download('task-report-' . now()->format('Ymd_His') . '.pdf');
    }

    private function buildUserReportQuery(Request $request)
    {
        $query = \App\Models\User::with('roles');

        if ($request->filled('name')) {
            $query->whereRaw("CONCAT(first_name, ' ', last_name) like ?", ['%' . $request->input('name') . '%']);
        }
        if ($request->filled('email')) {
            $query->where('email', 'like', '%' . $request->input('email') . '%');
        }
        if ($request->filled('role')) {
            $query->whereHas('roles', function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->input('role') . '%');
            });
        }

        return $query;
    }

    private function buildFolderStatsQuery(Request $request)
    {
        $query = \App\Models\Folder::with(['children', 'parent', 'creator'])->withCount('children');

        if ($request->filled('folder_name')) {
            $query->where('name', 'like', '%' . $request->input('folder_name') . '%');
        }

        if ($request->filled('user_name')) {
            $query->whereHas('creator', function ($q) use ($request) {
                $q->whereRaw("CONCAT(first_name, ' ', last_name) like ?", ['%' . $request->input('user_name') . '%']);
            });
        }

        return $query;
    }

    private function buildWorkflowReportQuery(Request $request)
    {
        $query = \App\Models\Workflow::with('createdBy');

        if ($request->filled('name')) {
            $query->where('name', 'like', '%' . $request->input('name') . '%');
        }
        if ($request->filled('status')) {
            $query->where('status', 'like', '%' . $request->input('status') . '%');
        }
        if ($request->filled('created_by')) {
            $query->whereHas('createdBy', function ($q) use ($request) {
                $q->whereRaw("CONCAT(first_name, ' ', last_name) like ?", ['%' . $request->input('created_by') . '%']);
            });
        }

        return $query;
    }

    private function buildTaskReportQuery(Request $request)
    {
        $query = \App\Models\WorkflowTask::with(['assignedUser', 'assignedRole', 'instance']);

        if ($request->filled('status')) {
            $query->where('status', 'like', '%' . $request->input('status') . '%');
        }
        if ($request->filled('assigned_user')) {
            $query->whereHas('assignedUser', function ($q) use ($request) {
                $q->whereRaw("CONCAT(first_name, ' ', last_name) like ?", ['%' . $request->input('assigned_user') . '%']);
            });
        }
        if ($request->filled('assigned_role')) {
            $query->whereHas('assignedRole', function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->input('assigned_role') . '%');
            });
        }
        if ($request->filled('workflow_instance')) {
            $query->whereHas('instance', function ($q) use ($request) {
                $q->where('id', $request->input('workflow_instance'));
            });
        }

        return $query;
    }
}
