<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Models\OperationsModel;
use App\Services\NotificationService;
use App\Models\ConferenceCommitteeModel;

final class OperationsController extends Controller
{
    public function attendanceIndex(): void
    {
        require_permission('attendance.view');
        $conferenceId = (int)
\request_conference_id();
        $model = new OperationsModel();

        $this->view('admin/attendance/index', [
            'conferences' => $model->conferences(),
            'conference_id' => $conferenceId,
            'rows' => $conferenceId > 0 ? $model->attendanceByConference($conferenceId) : [],
        ]);
    }

    public function attendanceCreate(): void
    {
        require_permission('attendance.manage');
        $model = new OperationsModel();

        if ($this->isPost()) {
            csrf_check();

            $old = $model->workflowBySubmission($submissionId);



            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'user_id' => (int) ($_POST['user_id'] ?? 0),
                'full_name_en' => trim((string) ($_POST['full_name_en'] ?? '')),
                'full_name_ar' => trim((string) ($_POST['full_name_ar'] ?? '')),
                'email' => trim((string) ($_POST['email'] ?? '')),
                'mobile' => trim((string) ($_POST['mobile'] ?? '')),
                'attendee_type' => trim((string) ($_POST['attendee_type'] ?? 'attendee')),
                'qr_token' => 'QR-' . bin2hex(random_bytes(8)),
                'notes' => trim((string) ($_POST['notes'] ?? '')),
            ];

            $model->createAttendance($data);
            flash('success', trans('save'));
            redirect('admin/attendance?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/attendance/create', [
            'conferences' => $model->conferences(),
        ]);
    }

    public function attendanceCheckin(): void
    {
        require_permission('attendance.manage');

        if ($this->isPost()) {
            csrf_check();
            $qr = trim((string) ($_POST['qr_token'] ?? ''));
            if ($qr !== '') {
                (new OperationsModel())->checkinByQr($qr, (int) auth_id());
            }
            flash('success', trans('attendance_checkin'));
        }

        redirect('admin/attendance');
    }

    public function presenterCheckin(): void
    {
        require_permission('attendance.manage');

        if ($this->isPost()) {
            csrf_check();
            $qr = trim((string) ($_POST['qr_token'] ?? ''));
            if ($qr !== '') {
                (new OperationsModel())->presenterCheckinByQr($qr);
            }
            flash('success', trans('presenter_checkin'));
        }

        redirect('admin/attendance');
    }

    public function paymentsIndex(): void
    {
        require_permission('payments.view');
        $conferenceId = (int)
\request_conference_id();
        $model = new OperationsModel();

        $this->view('admin/payments/index', [
            'conferences' => $model->conferences(),
            'conference_id' => $conferenceId,
            'rows' => $conferenceId > 0 ? $model->invoicesByConference($conferenceId) : [],
        ]);
    }

    public function paymentCreate(): void
    {
        require_permission('payments.manage');
        $model = new OperationsModel();

        if ($this->isPost()) {
            csrf_check();

            $data = [
                'conference_id' => (int) ($_POST['conference_id'] ?? 0),
                'submission_id' => (int) ($_POST['submission_id'] ?? 0),
                'user_id' => (int) ($_POST['user_id'] ?? 0),
                'invoice_no' => 'INV-' . date('YmdHis'),
                'amount' => (float) ($_POST['amount'] ?? 0),
                'currency' => trim((string) ($_POST['currency'] ?? 'JOD')),
                'invoice_type' => trim((string) ($_POST['invoice_type'] ?? 'registration')),
                'payment_status' => trim((string) ($_POST['payment_status'] ?? 'issued')),
                'notes' => trim((string) ($_POST['notes'] ?? '')),
            ];

            $model->createInvoice($data);
            flash('success', trans('save'));
            redirect('admin/payments?conference_id=' . $data['conference_id']);
        }

        $this->view('admin/payments/create', [
            'conferences' => $model->conferences(),
            'submissions' => $model->submissionsAll(),
        ]);
    }

    public function paymentMarkPaid(): void
    {
        require_permission('payments.manage');

        if ($this->isPost()) {
            csrf_check();
            $invoiceId = (int) ($_POST['invoice_id'] ?? 0);
            $amount = (float) ($_POST['amount'] ?? 0);
            (new OperationsModel())->markInvoicePaid($invoiceId, $amount);
            flash('success', trans('paid'));
        }

        redirect('admin/payments');
    }

    public function emailTemplatesIndex(): void
    {
        require_permission('email_templates.view');
        $this->view('admin/email_templates/index', [
            'rows' => (new OperationsModel())->emailTemplates(),
        ]);
    }

    public function emailTemplateEdit(): void
    {
        require_permission('email_templates.manage');
        $model = new OperationsModel();
        $id = (int) ($_GET['id'] ?? 0);
        $row = $model->emailTemplateById($id);
        if (!$row) redirect('admin/email-templates');

        if ($this->isPost()) {
            csrf_check();
            $model->updateEmailTemplate($id, [
                'subject_en' => trim((string) ($_POST['subject_en'] ?? '')),
                'subject_ar' => trim((string) ($_POST['subject_ar'] ?? '')),
                'body_en' => trim((string) ($_POST['body_en'] ?? '')),
                'body_ar' => trim((string) ($_POST['body_ar'] ?? '')),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ]);
            flash('success', trans('save'));
            redirect('admin/email-templates');
        }

        $this->view('admin/email_templates/edit', ['row' => $row]);
    }

    public function authorWorkflowIndex(): void
    {
        require_permission('author_workflows.view');
        $model = new OperationsModel();
        $rows = $model->submissionsAll();

        $this->view('admin/author_workflow/index', [
            'rows' => $rows,
            'model' => $model,
        ]);
    }

    public function authorWorkflowEdit(): void
    {
        require_permission('author_workflows.manage');
        $model = new OperationsModel();
        $submissionId = (int) ($_GET['submission_id'] ?? ($_POST['submission_id'] ?? 0));
        if ($submissionId <= 0) redirect('admin/author-workflow');

        $workflow = $model->workflowBySubmission($submissionId);

        if ($this->isPost()) {
            csrf_check();
            $model->saveWorkflow([
                'submission_id' => $submissionId,
                'workflow_stage' => trim((string) ($_POST['workflow_stage'] ?? 'submission')),
                'workflow_status' => trim((string) ($_POST['workflow_status'] ?? 'pending')),
                'notes_en' => trim((string) ($_POST['notes_en'] ?? '')),
                'notes_ar' => trim((string) ($_POST['notes_ar'] ?? '')),
                'updated_by' => auth_id(),
            ]);

            // Notify author if stage/status changed
            $new = $model->workflowBySubmission($submissionId);
            if ($old && $new) {
                $oldStage = (string) ($old['workflow_stage'] ?? '');
                $newStage = (string) ($new['workflow_stage'] ?? '');
                $oldStatus = (string) ($old['workflow_status'] ?? '');
                $newStatus = (string) ($new['workflow_status'] ?? '');

                if ($oldStage !== $newStage || $oldStatus !== $newStatus) {
                    $db = \App\Core\Database::getInstance();
                    $st = $db->prepare("SELECT author_id, submission_no FROM submissions WHERE id = :id LIMIT 1");
                    $st->execute([':id' => $submissionId]);
                    $srow = $st->fetch();
                    if ($srow && !empty($srow['author_id'])) {
                        NotificationService::push(
                            (int) $srow['author_id'],
                            'workflow',
                            trans('stage_changed') . ' — ' . (string) ($srow['submission_no'] ?? '')
                        );
                        NotificationService::pushEmailFromTemplate('decision_notification', (int)$srow['author_id'], [
                            'name' => '',
                            'submission_no' => (string) ($srow['submission_no'] ?? ''),
                            'lang' => current_lang(),
                        ]);
                    }
                }
            }

            flash('success', trans('save'));
            redirect('admin/author-workflow');
        }

        $submission = null;
        foreach ($model->submissionsAll() as $row) {
            if ((int) $row['id'] === $submissionId) {
                $submission = $row;
                break;
            }
        }

        $this->view('admin/author_workflow/edit', [
            'workflow' => $workflow,
            'submission' => $submission,
        ]);
    }

    public function openReviewRound(): void
    {
        require_permission('review_rounds.manage');

        if ($this->isPost()) {
            csrf_check();
            $submissionId = (int) ($_POST['submission_id'] ?? 0);
            $notesEn = trim((string) ($_POST['notes_en'] ?? ''));
            $notesAr = trim((string) ($_POST['notes_ar'] ?? ''));
            (new OperationsModel())->openNextRound($submissionId, (int) auth_id(), $notesEn, $notesAr);
            flash('success', trans('open_round'));
        }

        redirect('admin/author-workflow');
    }

    public function closeReviewRound(): void
    {
        require_permission('review_rounds.manage');

        if ($this->isPost()) {
            csrf_check();
            $roundId = (int) ($_POST['round_id'] ?? 0);
            (new OperationsModel())->closeRound($roundId);
            flash('success', trans('close_round'));
        }

        redirect('admin/author-workflow');
    }

    public function tpcCertificate(): void
    {
        require_permission('conference_certificates.print');

        $conferenceId = (int)
\request_conference_id();
        $email = trim((string) ($_GET['email'] ?? ''));

        $model = new OperationsModel();
        if (!$model->tpcCertificateEligible($email, $conferenceId)) {
            http_response_code(403);
            exit('TPC certificate not eligible');
        }

        $conference = null;
        foreach ($model->conferences() as $c) {
            if ((int) $c['id'] === $conferenceId) {
                $conference = $c;
                break;
            }
        }

        $member = null;
        foreach ((new ConferenceCommitteeModel())->byConference($conferenceId) as $m) {
            if (($m['email'] ?? '') === $email && ($m['committee_type'] ?? '') === 'tpc') {
                $member = $m;
                break;
            }
        }

        require __DIR__ . '/../views/print/tpc_certificate.php';
    }
    public function emailQueueIndex(): void
    {
        require_permission('email_queue.view');
        $this->view('admin/email_queue/index', [
            'rows' => (new \App\Services\MailQueueService())->rows(200),
        ]);
    }

    public function emailQueueTest(): void
    {
        require_permission('email_queue.manage');

        if ($this->isPost()) {
            csrf_check();

            $to = trim((string) ($_POST['to_email'] ?? ''));
            $name = trim((string) ($_POST['to_name'] ?? ''));
            if ($to !== '') {
                (new \App\Services\MailQueueService())->queue(
                    $to,
                    'EasyChair Test Email',
                    '<p>This is a queued test email from EasyChair Portal.</p>',
                    'test_email',
                    $name
                );
                flash('success', trans('email_triggered'));
            }
        }

        redirect('admin/email-queue');
    }

    public function reviewerCertificate(): void
    {
        require_permission('conference_certificates.print');

        $conferenceId = (int)
\request_conference_id();
        $reviewerId = (int) ($_GET['reviewer_id'] ?? 0);

        $model = new OperationsModel();
        if (!$model->reviewerCertificateEligible($reviewerId, $conferenceId)) {
            http_response_code(403);
            exit('Reviewer certificate not eligible');
        }

        $conference = null;
        foreach ($model->conferences() as $c) {
            if ((int) $c['id'] === $conferenceId) {
                $conference = $c;
                break;
            }
        }

        $db = \App\Core\Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $reviewerId]);
        $reviewer = $stmt->fetch();

        require __DIR__ . '/../views/print/reviewer_certificate.php';
    }

}
