<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use App\Models\Conference;
use App\Services\MailTemplateService;

final class RegistrationController extends Controller
{
    public function builder(): void
    {
        require_permission('registration_forms.manage');

        $conferenceId = (int) ($_GET['conference_id'] ?? ($_POST['conference_id'] ?? 0));
        $db = Database::getInstance();
        $conferenceModel = new Conference();

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

            $stmt = $db->prepare("
                INSERT INTO registration_form_settings (
                    conference_id, title_en, title_ar, intro_en, intro_ar, is_enabled
                ) VALUES (
                    :conference_id, :title_en, :title_ar, :intro_en, :intro_ar, :is_enabled
                )
                ON DUPLICATE KEY UPDATE
                    title_en = VALUES(title_en),
                    title_ar = VALUES(title_ar),
                    intro_en = VALUES(intro_en),
                    intro_ar = VALUES(intro_ar),
                    is_enabled = VALUES(is_enabled)
            ");
            $stmt->execute([
                ':conference_id' => $conferenceId,
                ':title_en' => trim((string) ($_POST['title_en'] ?? '')),
                ':title_ar' => trim((string) ($_POST['title_ar'] ?? '')),
                ':intro_en' => trim((string) ($_POST['intro_en'] ?? '')),
                ':intro_ar' => trim((string) ($_POST['intro_ar'] ?? '')),
                ':is_enabled' => isset($_POST['is_enabled']) ? 1 : 0,
            ]);

            flash('success', trans('save'));
            redirect('admin/registration-form?conference_id=' . $conferenceId);
        }

        $row = null;
        if ($conferenceId > 0) {
            $stmt = $db->prepare("SELECT * FROM registration_form_settings WHERE conference_id = :conference_id LIMIT 1");
            $stmt->execute([':conference_id' => $conferenceId]);
            $row = $stmt->fetch() ?: null;
        }

        $this->view('admin/registration_form/builder', [
            'conferences' => $conferenceModel->all(),
            'conference_id' => $conferenceId,
            'row' => $row,
        ]);
    }

    public function publicForm(): void
    {
        $conferenceId = (int) ($_GET['conference_id'] ?? ($_POST['conference_id'] ?? 0));
        if ($conferenceId <= 0) {
            redirect('');
        }

        $db = Database::getInstance();
        $conferenceModel = new Conference();
        $conference = $conferenceModel->findById($conferenceId);
        if (!$conference || empty($conference['is_active'])) {
            http_response_code(404);
            exit('Conference not found');
        }

        $stmt = $db->prepare("SELECT * FROM registration_form_settings WHERE conference_id = :conference_id LIMIT 1");
        $stmt->execute([':conference_id' => $conferenceId]);
        $settings = $stmt->fetch() ?: null;

        $cf = $db->prepare("
            SELECT *
            FROM custom_fields
            WHERE module_name = 'registration'
              AND is_active = 1
            ORDER BY sort_order ASC, id ASC
        ");
        $cf->execute();
        $fields = $cf->fetchAll();

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

            $payload = [];
            foreach ($fields as $field) {
                $key = (string) $field['field_key'];
                $payload[$key] = $_POST['cf'][$key] ?? null;
            }

            $stmt = $db->prepare("
                INSERT INTO registration_submissions (
                    conference_id, user_id, full_name_en, full_name_ar, email, mobile, data_json, status
                ) VALUES (
                    :conference_id, :user_id, :full_name_en, :full_name_ar, :email, :mobile, :data_json, 'pending'
                )
            ");
            $stmt->execute([
                ':conference_id' => $conferenceId,
                ':user_id' => auth_id(),
                ':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'] ?? '')),
                ':data_json' => json_encode($payload, JSON_UNESCAPED_UNICODE),
            ]);

            $email = trim((string) ($_POST['email'] ?? ''));
            $name = trim((string) ($_POST['full_name_en'] ?? ''));
            if ($email !== '') {
                MailTemplateService::queue('submission_ack', $email, $name, [
                    'name' => $name,
                    'submission_no' => 'REG-' . $db->lastInsertId(),
                    'lang' => current_lang(),
                ]);
            }

            flash('success', trans('save'));
            redirect('register/conference?conference_id=' . $conferenceId);
        }

        $this->view('registration/public_form', [
            'conference' => $conference,
            'settings' => $settings,
            'fields' => $fields,
        ]);
    }

    public function submissionsIndex(): void
    {
        require_permission('registration_forms.view');
        $conferenceId = (int)
\request_conference_id();

        $db = Database::getInstance();
        $rows = [];
        if ($conferenceId > 0) {
            $stmt = $db->prepare("
                SELECT *
                FROM registration_submissions
                WHERE conference_id = :conference_id
                ORDER BY id DESC
            ");
            $stmt->execute([':conference_id' => $conferenceId]);
            $rows = $stmt->fetchAll();
        }

        $this->view('admin/registration_form/submissions', [
            'conferences' => (new Conference())->all(),
            'conference_id' => $conferenceId,
            'rows' => $rows,
        ]);
    }

    public function submissionUpdate(): void
    {
        require_permission('registration_forms.manage');

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

            $id = (int) ($_POST['id'] ?? 0);
            $status = trim((string) ($_POST['status'] ?? 'pending'));

            $db = Database::getInstance();
            $stmt = $db->prepare("UPDATE registration_submissions SET status = :status WHERE id = :id");
            $stmt->execute([
                ':status' => $status,
                ':id' => $id,
            ]);

            flash('success', trans('save'));
        }

        redirect('admin/registration-submissions?conference_id=' . (int) ($_POST['conference_id'] ?? 0));
    }
}
