<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GenerateWebsite;
use App\Models\NotificationLog;
use App\Models\Subscription;
use App\Models\Transaction;
use App\Models\UserLogin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use ZipArchive;

class ReportController extends Controller {

    public function transactions(Request $request, $userId = null) {
        $pageTitle = 'Transaction Logs';

        $remarks = Transaction::distinct('remark')->orderBy('remark')->get('remark');

        $transactions = Transaction::searchable(['trx', 'user:username'])->filter(['trx_type', 'remark'])->dateFilter()->orderBy('id', 'desc')->with('user');
        if ($userId) {
            $transactions = $transactions->where('user_id', $userId);
        }
        $transactions = $transactions->paginate(getPaginate());

        return view('admin.reports.transactions', compact('pageTitle', 'transactions', 'remarks'));
    }


    public function subscriptions(Request $request, $userId = null) {
        $pageTitle     = 'Subscription History';
        $subscriptions = Subscription::searchable(['user:username', 'plan:name'])->dateFilter()->orderBy('id', 'desc')->with(['user', 'plan'])->paginate(getPaginate());
        return view('admin.reports.subscriptions', compact('pageTitle', 'subscriptions', ));
    }
    public function generatedWebsite(Request $request, $userId = null) {
        $pageTitle         = 'Generated Website History';
        $generatedWebsites = GenerateWebsite::searchable(['user:username', 'websiteType:name'])->orderBy('id', 'desc')->with(['user', 'websiteType'])->paginate(getPaginate());
        return view('admin.reports.websites', compact('pageTitle', 'generatedWebsites', ));
    }

    public function websiteDownload($id) {
        $generateWebsite = GenerateWebsite::where('id', $id)->firstOrFail();

        $zipFileName = 'website_' . $generateWebsite->id . '.zip';
        $zipPath     = storage_path('app/' . $zipFileName);
        $zip         = new ZipArchive;
        if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
            $files = File::files(getFilePath('websites') . '/' . $generateWebsite->folder_name);
            foreach ($files as $file) {
                $zip->addFile($file->getRealPath(), $file->getFilename());
            }
            $zip->close();
        } else {
            return response()->json(['error' => 'Failed to create ZIP.']);
        }
        return response()->download($zipPath)->deleteFileAfterSend(true);

    }

    public function websitePreview($slug, $path = null) {
        $generateWebsite = GenerateWebsite::where('folder_name', $slug)->first();
        $basePath        = getFilePath('websites') . '/' . $generateWebsite->folder_name;
        $files           = File::files(getFilePath('websites') . '/' . $generateWebsite->folder_name);

        $previewFile = '';
        foreach ($files as $key => $file) {
            $filename = basename($file);
            if ($filename == 'index.html' || $filename == 'home.html') {
                $previewFile = $filename;
                break;
            }
        }

        if (!$previewFile) {
            $previewFile = $files[0]->getFilename();
        }

        $fullPath = $basePath . '/' . $previewFile;
        if (!File::exists($fullPath)) {
            abort(404);
        }
        return redirect()->to(asset($fullPath));

    }

    public function loginHistory(Request $request) {
        $pageTitle = 'User Login History';
        $loginLogs = UserLogin::orderBy('id', 'desc')->searchable(['user:username'])->dateFilter()->with('user')->paginate(getPaginate());
        return view('admin.reports.logins', compact('pageTitle', 'loginLogs'));
    }

    public function loginIpHistory($ip) {
        $pageTitle = 'Login by - ' . $ip;
        $loginLogs = UserLogin::where('user_ip', $ip)->orderBy('id', 'desc')->with('user')->paginate(getPaginate());
        return view('admin.reports.logins', compact('pageTitle', 'loginLogs', 'ip'));
    }

    public function notificationHistory(Request $request) {
        $pageTitle = 'Notification History';
        $logs      = NotificationLog::orderBy('id', 'desc')->searchable(['user:username'])->dateFilter()->with('user')->paginate(getPaginate());
        return view('admin.reports.notification_history', compact('pageTitle', 'logs'));
    }

    public function emailDetails($id) {
        $pageTitle = 'Email Details';
        $email     = NotificationLog::findOrFail($id);
        return view('admin.reports.email_details', compact('pageTitle', 'email'));
    }
}
