<?php

namespace Dashboard\Controllers\AI;

use Dashboard\Core\Controller;
use Dashboard\Services\AiService;
use Exception;

class DataSourceController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_AI');
    }

    public function index()
    {
		    try {
			    $subscription = AiService::getSubscription();
		    } catch (Exception $e) {
			    return view('ai.error', ['error' => $e->getMessage()]);
		    }
		    
		    if (!$subscription) {
			    return view('ai.subscribe');
		    }
				
				$dataSources = $subscription["data_sources"] ?? [];
				
        return view('ai.data', compact('subscription', 'dataSources'));
    }
    public function process()
    {
        validate([
            'dataSourceType' => 'required|in:file,sitemap',
            'file' => 'required_if:dataSourceType,file|uploaded_file|max:10M|mimes:pdf,csv,txt,xlsx,md,mdx,xml,json,docx',
	          'sitemapUrl' => 'required_if:dataSourceType,sitemap|url',
        ]);
				
				try {
					if (input('dataSourceType') === 'file') {
						AiService::uploadFile($_FILES['file']);
					}
					if (input('dataSourceType') === 'sitemap') {
						AiService::addSitemap(input('sitemapUrl'));
					}
				} catch (Exception $e) {
					return back()->flash("error", t__('An error occurred while processing the data source: %error%', ['%error%' => $e->getMessage()]));
				}

        return back()->flash("success", t__('Data source has been uploaded successfully! We will process it shortly.'));
    }
		
		public function destroy($id)
		{
			try {
				AiService::deleteDataSource($id);
				
				return back()->flash("success", t__('Data source has been deleted successfully!'));
			} catch (Exception $e) {
				return back()->flash("error", t__('An error occurred while deleting the data source: %error%', ['%error%' => $e->getMessage()]));
			}
		}
}