<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Services\Import\BulkImportService;
use App\Services\Import\SimpleXlsx;
use Throwable;

final class BulkImportController
{
    private BulkImportService $service;

    public function __construct()
    {
        $this->service = new BulkImportService(DB::pdo());
    }

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('admin.import_data');
        $jobId = (int)Request::get('job_id', 0);
        $jobs = [];
        $job = false;
        $rows = [];
        $schemaError = '';
        try {
            $this->service->ensureSchema();
            $jobs = $this->service->recentJobs();
            $job = $jobId > 0 ? $this->service->job($jobId) : false;
            $rows = $jobId > 0 ? $this->service->rows($jobId, 500) : [];
        } catch (Throwable $e) {
            $schemaError = $e->getMessage();
        }
        Response::view('pages/admin/import/index', [
            'types' => $this->service->types(),
            'jobs' => $jobs,
            'job' => $job,
            'rows' => $rows,
            'schemaError' => $schemaError,
        ]);
    }

    public function template(): void
    {
        Auth::requireLogin();
        require_permission('admin.import_data');
        $type = (string)Request::get('type', 'items');
        if (!isset($this->service->types()[$type])) {
            $type = 'items';
        }
        SimpleXlsx::output('template_' . $type . '.xlsx', $this->service->templateRows($type));
    }

    public function upload(): void
    {
        Auth::requireLogin();
        require_permission('admin.import_data');
        try {
            Csrf::verify();
            $type = (string)Request::post('import_type', 'items');
            $jobId = $this->service->createJobFromUpload($type, $_FILES['excel_file'] ?? [], Auth::id());
            Response::flash('success', 'تم تحليل الملف. راجع النتائج قبل التنفيذ.');
            Response::redirect('/admin/import-data?job_id=' . $jobId);
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
            Response::redirect('/admin/import-data');
        }
    }

    public function execute(): void
    {
        Auth::requireLogin();
        require_permission('admin.import_data');
        try {
            Csrf::verify();
            $jobId = (int)Request::post('job_id', 0);
            $result = $this->service->executeJob($jobId);
            Response::flash('success', 'تم التنفيذ. تمت إضافة ' . $result['imported'] . ' صف، وتخطي ' . $result['skipped'] . ' مكرر.');
            Response::redirect('/admin/import-data?job_id=' . $jobId);
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
            Response::redirect('/admin/import-data');
        }
    }

    public function clearLogs(): void
    {
        Auth::requireLogin();
        require_permission('admin.import_data');
        try {
            Csrf::verify();
            $deleted = $this->service->clearLogs();
            Response::flash('success', 'تم حذف سجلات الاستيراد السابقة (' . $deleted . ' عملية).');
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
        }
        Response::redirect('/admin/import-data');
    }
}
