<?php
declare(strict_types=1);

namespace App\Modules\Archive\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Archive\Models\ArchiveSnapshot;
use App\Modules\Archive\Services\ArchiveService;

class ArchiveController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'entity_type'       => $request->get('entity_type', ''),
            'membership_number' => $request->get('membership_number', ''),
            'snapshot_reason'   => $request->get('snapshot_reason', ''),
            'date_from'         => $request->get('date_from', ''),
            'date_to'           => $request->get('date_to', ''),
            'search'            => trim((string) $request->get('q', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = ArchiveSnapshot::search($filters, 25, $page);

        $entityTypes = ArchiveSnapshot::getDistinctEntityTypes();
        $reasons = ArchiveSnapshot::getDistinctReasons();

        return $this->view('Archive.Views.index', [
            'rows'        => $result['data'],
            'pagination'  => $result['pagination'],
            'filters'     => $filters,
            'entityTypes' => $entityTypes,
            'reasons'     => $reasons,
        ]);
    }

    public function show(Request $request, string $id): Response
    {
        $snapshot = ArchiveService::getSnapshot((int) $id);
        if (!$snapshot) {
            return $this->redirect('/archive')->withError('اللقطة الأرشيفية غير موجودة');
        }

        // Get other snapshots for same entity for navigation
        $otherSnapshots = ArchiveSnapshot::getForEntity($snapshot['entity_type'], (int) $snapshot['entity_id']);

        return $this->view('Archive.Views.show', [
            'snapshot'       => $snapshot,
            'otherSnapshots' => $otherSnapshots,
        ]);
    }

    public function compare(Request $request, string $id1, string $id2): Response
    {
        try {
            $diff = ArchiveService::compareSnapshots((int) $id1, (int) $id2);
        } catch (\RuntimeException $e) {
            return $this->redirect('/archive')->withError($e->getMessage());
        }

        $snap1 = ArchiveService::getSnapshot((int) $id1);
        $snap2 = ArchiveService::getSnapshot((int) $id2);

        return $this->view('Archive.Views.compare', [
            'diff'  => $diff,
            'snap1' => $snap1,
            'snap2' => $snap2,
        ]);
    }

    public function entitySnapshots(Request $request, string $type, string $id): Response
    {
        $snapshots = ArchiveService::getSnapshots($type, (int) $id);

        return $this->view('Archive.Views.index', [
            'rows'        => $snapshots,
            'pagination'  => ['last_page' => 1, 'current_page' => 1],
            'filters'     => ['entity_type' => $type, 'search' => '', 'membership_number' => '', 'snapshot_reason' => '', 'date_from' => '', 'date_to' => ''],
            'entityTypes' => ArchiveSnapshot::getDistinctEntityTypes(),
            'reasons'     => ArchiveSnapshot::getDistinctReasons(),
            'entityFilter' => ['type' => $type, 'id' => (int) $id],
        ]);
    }

    public function numberChain(Request $request, string $number): Response
    {
        $chain = ArchiveService::getNumberChain($number);
        $snapshots = ArchiveSnapshot::getByMembershipNumber($number);

        return $this->view('Archive.Views.show', [
            'snapshot'       => null,
            'otherSnapshots' => $snapshots,
            'numberChain'    => $chain,
            'membershipNumber' => $number,
            'isChainView'    => true,
        ]);
    }

    public function takeManual(Request $request): Response
    {
        $entityType = trim((string) $request->post('entity_type', ''));
        $entityId = (int) $request->post('entity_id', 0);
        $reason = trim((string) $request->post('reason', 'manual'));
        $notes = trim((string) $request->post('notes', ''));

        if ($entityType === '' || $entityId <= 0) {
            return $this->redirect('/archive')->withError('بيانات غير مكتملة');
        }

        try {
            $snapshotId = ArchiveService::takeSnapshot(
                $entityType,
                $entityId,
                $reason,
                $notes ?: null
            );
            return $this->redirect("/archive/{$snapshotId}")->withSuccess('تم أخذ اللقطة الأرشيفية بنجاح');
        } catch (\RuntimeException $e) {
            return $this->redirect('/archive')->withError('فشل أخذ اللقطة: ' . $e->getMessage());
        }
    }
}