<?php
declare(strict_types=1);

namespace App\Modules\Fines\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Core\Logger;
use App\Modules\Fines\Models\Violation;
use App\Modules\Workflow\Services\WorkflowEngine;

class ViolationController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'search' => trim((string) $request->get('q', '')),
            'status' => $request->get('status', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = Violation::search($filters, 25, $page);

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

    public function create(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) return $this->redirect('/members')->withError('العضو غير موجود');

        return $this->view('Fines.Views.violations.create', ['member' => $member]);
    }

    public function store(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) return $this->redirect('/members')->withError('العضو غير موجود');

        $description = trim((string) $request->post('description', ''));
        $violationDate = $request->post('violation_date', date('Y-m-d'));
        $evidence = trim((string) $request->post('evidence_notes', ''));

        if ($description === '') return $this->redirect("/violations/create/{$memberId}")->withError('وصف المخالفة مطلوب');

        $employee = App::getInstance()->currentEmployee();

        $proofFilePath = null;
        if (!empty($_FILES['proof_file']['tmp_name']) && $_FILES['proof_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['proof_file'];
            $maxSize = 5 * 1024 * 1024;
            if ($file['size'] > $maxSize) {
                return $this->redirect("/violations/create/{$memberId}")->withError('حجم الملف يتجاوز الحد الأقصى (5 ميجا)');
            }
            $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf',
                        'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            if (!in_array($file['type'], $allowed)) {
                return $this->redirect("/violations/create/{$memberId}")->withError('نوع الملف غير مسموح');
            }
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $storedName = 'violation_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $destDir = App::getInstance()->basePath() . '/public/storage/uploads/violations';
            if (!is_dir($destDir)) {
                mkdir($destDir, 0755, true);
            }
            move_uploaded_file($file['tmp_name'], $destDir . '/' . $storedName);
            $proofFilePath = 'storage/uploads/violations/' . $storedName;
        }

        $violation = Violation::create([
            'member_id'      => (int) $memberId,
            'violation_date' => $violationDate,
            'description'    => $description,
            'reported_by'    => $employee ? (int) $employee->id : null,
            'evidence_notes' => $evidence ?: null,
            'proof_file'     => $proofFilePath,
            'status'         => 'reported',
        ]);

        if (WorkflowEngine::hasDefinition('violation_penalty')) {
            try {
                WorkflowEngine::createInstance('violation_penalty', 'violations', (int) $violation->id);
            } catch (\Throwable $e) {
                Logger::warning("Workflow instance creation failed for violation", ['violation_id' => (int) $violation->id, 'error' => $e->getMessage()]);
            }
        }

        EventBus::dispatch('violation.reported', ['violation_id' => (int) $violation->id, 'member_id' => (int) $memberId]);

        return $this->redirect('/violations')->withSuccess('تم تسجيل المخالفة');
    }
}