<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Repositories\HouseholdRepository;
use App\Repositories\TerritoryRepository;
use App\Services\ExportService;
use Core\Controller;
use Core\Request;
use Core\Response;

class ExportController extends Controller
{
    public function generate(): Response
    {
        if ($redirect = $this->requireAuth()) {
            return $redirect;
        }

        $territories = (new TerritoryRepository(database()))->allOrdered();

        return $this->view('export.generate', [
            'pageTitle'   => 'Export Territories',
            'territories' => $territories,
        ]);
    }

    public function download(): Response
    {
        if ($redirect = $this->requireAuth()) {
            return $redirect;
        }

        $request = Request::capture();

        if (!verify_csrf_token($request->input('_token'))) {
            flash('error', 'Invalid request.');
            return $this->redirect('/export');
        }

        $selectedIds = $request->input('territory_ids');

        if (!is_array($selectedIds) || empty($selectedIds)) {
            flash('error', 'Please select at least one territory to export.');
            return $this->redirect('/export');
        }

        $ids = array_map('intval', $selectedIds);
        $ids = array_filter($ids, fn(int $id) => $id > 0);

        if (empty($ids)) {
            flash('error', 'Please select at least one territory to export.');
            return $this->redirect('/export');
        }

        $territoryRepo = new TerritoryRepository(database());
        $territories   = array_filter(
            array_map(fn(int $id) => $territoryRepo->find($id), $ids)
        );

        if (empty($territories)) {
            flash('error', 'Selected territories not found.');
            return $this->redirect('/export');
        }

        $households = (new HouseholdRepository(database()))->findAllByTerritories($ids);
        $zip        = (new ExportService())->buildZip(array_values($territories), $households);
        $filename   = 'territory_export_' . date('Ymd_His') . '.zip';

        return $this->fileResponse($zip, $filename, 'application/zip');
    }
}
