<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Core\Database;
use App\Services\NotificationService;

final class CopyeditorController extends Controller
{
    public function workspace(): void
    {
        require_login();
        require_permission('copyeditor.workspace');

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

        $stmt = $db->prepare("
            SELECT ca.*, s.submission_no, s.title, s.title_ar, s.author_id,
                   c.title_en AS conference_title_en, c.title_ar AS conference_title_ar
            FROM copyediting_assignments ca
            INNER JOIN submissions s ON s.id = ca.submission_id
            LEFT JOIN conferences c ON c.id = s.conference_id
            WHERE ca.copyeditor_id = :uid
            ORDER BY FIELD(ca.status,'assigned','in_progress','returned','completed'), ca.due_date ASC, ca.id DESC
        ");
        $stmt->execute([':uid' => $uid]);
        $rows = $stmt->fetchAll();

        $this->view('copyeditor/workspace', ['rows' => $rows]);
    }

    public function update(): void
    {
        require_login();
        require_permission('copyeditor.workspace');

        if (!$this->isPost()) redirect('copyeditor/workspace');
        csrf_check();

        $submissionId = (int) ($_POST['submission_id'] ?? 0);
        $status = trim((string) ($_POST['status'] ?? 'in_progress'));
        $notesEn = trim((string) ($_POST['notes_en'] ?? ''));
        $notesAr = trim((string) ($_POST['notes_ar'] ?? ''));

        $db = Database::getInstance();
        $stmt = $db->prepare("
            UPDATE copyediting_assignments
            SET status = :status,
                notes_en = :notes_en,
                notes_ar = :notes_ar
            WHERE submission_id = :submission_id
              AND copyeditor_id = :uid
        ");
        $stmt->execute([
            ':status' => $status,
            ':notes_en' => $notesEn ?: null,
            ':notes_ar' => $notesAr ?: null,
            ':submission_id' => $submissionId,
            ':uid' => (int) auth_id(),
        ]);

        // Notify author (in-app) that copyediting updated
        $stmt = $db->prepare("SELECT author_id, submission_no FROM submissions WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $submissionId]);
        $s = $stmt->fetch();

        if ($s && !empty($s['author_id'])) {
            NotificationService::push(
                (int)$s['author_id'],
                'copyediting',
                trans('copyediting_updated') . ' — ' . (string)($s['submission_no'] ?? '')
            );
        }

        flash('success', trans('save'));
        redirect('copyeditor/workspace');
    }
}
