<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

final class AuthorSubmissionEditController extends Controller
{
    private function cleanText(string $s): string
    {
        $s = trim($s);
        $s = preg_replace("/\r\n|\r/u", "\n", $s);
        return $s;
    }

    private function cleanKeywords(string $s): string
    {
        // comma-separated; remove duplicate/empty; keep short
        $parts = preg_split('/[,]+/u', $s);
        $out = [];
        foreach ($parts as $p) {
            $k = trim((string)$p);
            if ($k === '') continue;
            $k = mb_substr($k, 0, 40);
            $out[] = $k;
        }
        // unique while preserving order
        $seen = [];
        $uniq = [];
        foreach ($out as $k) {
            $lk = mb_strtolower($k);
            if (isset($seen[$lk])) continue;
            $seen[$lk] = true;
            $uniq[] = $k;
        }
        return implode(', ', $uniq);
    }

    public function edit(): void
    {
        require_login();
        $db = Database::getInstance();
        $uid = (int)auth_id();

        $id = (int)($_GET['id'] ?? 0);
        $st = $db->prepare("SELECT * FROM submissions WHERE id=:id AND author_id=:uid LIMIT 1");
        $st->execute([':id'=>$id, ':uid'=>$uid]);
        $row = $st->fetch();
        if (!$row) { http_response_code(404); exit('Not found'); }

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

    public function update(): void
    {
        require_login();
        if (!$this->isPost()) redirect('author/submissions');
        csrf_check();

        $db = Database::getInstance();
        $uid = (int)auth_id();

        $id = (int)($_POST['id'] ?? 0);

        $st = $db->prepare("SELECT * FROM submissions WHERE id=:id AND author_id=:uid LIMIT 1");
        $st->execute([':id'=>$id, ':uid'=>$uid]);
        $row = $st->fetch();
        if (!$row) { http_response_code(403); exit('Forbidden'); }

        // Required bilingual fields
        $titleEn = $this->cleanText((string)($_POST['title'] ?? ''));
        $titleAr = $this->cleanText((string)($_POST['title_ar'] ?? ''));
        $absEn   = $this->cleanText((string)($_POST['abstract'] ?? ''));
        $absAr   = $this->cleanText((string)($_POST['abstract_ar'] ?? ''));

        $kwEn = $this->cleanKeywords((string)($_POST['keywords'] ?? ''));
        $kwAr = $this->cleanKeywords((string)($_POST['keywords_ar'] ?? ''));

        if ($titleEn==='' || $titleAr==='' || $absEn==='' || $absAr==='' || $kwEn==='' || $kwAr==='') {
            flash('danger', trans('required_fields'));
            redirect('author/submission/edit?id='.$id);
        }

        // Update
        $up = $db->prepare("
            UPDATE submissions
            SET title=:te,
                title_ar=:ta,
                abstract=:ae,
                abstract_ar=:aa,
                keywords=:ke,
                keywords_ar=:ka
            WHERE id=:id AND author_id=:uid
        ");
        $up->execute([
            ':te'=>$titleEn,
            ':ta'=>$titleAr,
            ':ae'=>$absEn,
            ':aa'=>$absAr,
            ':ke'=>$kwEn,
            ':ka'=>$kwAr,
            ':id'=>$id,
            ':uid'=>$uid
        ]);

        flash('success', trans('save'));
        redirect('author/submissions');
    }
}
