<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

final class AuthorWorkController extends Controller
{
    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=:u LIMIT 1");
        $st->execute([':id'=>$id, ':u'=>$uid]);
        $row = $st->fetch();
        if (!$row) { http_response_code(404); echo "Not found"; return; }

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

    public function save(): void
    {
        require_login();
        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=:u LIMIT 1");
        $st->execute([':id'=>$id, ':u'=>$uid]);
        $row = $st->fetch();
        if (!$row) { http_response_code(404); echo "Not found"; return; }

        $title_en = trim((string)($_POST['title_en'] ?? ''));
        $title_ar = trim((string)($_POST['title_ar'] ?? ''));
        if ($title_en==='' || $title_ar==='') {
            $this->view('author/edit', ['row'=>$row, 'err'=>'Title AR/EN required']);
            return;
        }

        // Best effort columns
        $cols = $db->query("SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='submissions'")->fetchColumn();
        $set = array_flip(explode(',', (string)$cols));

        $updates=[]; $params=[':id'=>$id, ':u'=>$uid];
        if (isset($set['title_en'])) { $updates[]="title_en=:te"; $params[':te']=$title_en; }
        if (isset($set['title_ar'])) { $updates[]="title_ar=:ta"; $params[':ta']=$title_ar; }
        if (!$updates && isset($set['title'])) { $updates[]="title=:te"; $params[':te']=$title_en; }

        foreach (['abstract_en','abstract_ar','keywords_en','keywords_ar'] as $c) {
            if (isset($set[$c])) { $updates[]="$c=:$c"; $params[":$c"]=(string)($_POST[$c] ?? ''); }
        }

        if ($updates) {
            $db->prepare("UPDATE submissions SET ".implode(',', $updates)." WHERE id=:id AND author_id=:u")->execute($params);
        }

        header('Location: ' . base_path('author/submission?id='.$id));
        exit;
    }

    public function withdraw(): void
    {
        require_login();
        csrf_check();
        $db = Database::getInstance();
        $uid = (int)auth_id();
        $id = (int)($_POST['id'] ?? 0);

        $st = $db->prepare("SELECT status FROM submissions WHERE id=:id AND author_id=:u LIMIT 1");
        $st->execute([':id'=>$id, ':u'=>$uid]);
        $status = (string)($st->fetchColumn() ?: '');
        if ($status === '') { http_response_code(404); echo "Not found"; return; }

        // allow withdraw unless published
        if ($status === 'published') { http_response_code(403); echo "Forbidden"; return; }

        $db->prepare("UPDATE submissions SET status='archived' WHERE id=:id AND author_id=:u")->execute([':id'=>$id, ':u'=>$uid]);
        header('Location: ' . base_path('author/submissions'));
        exit;
    }
}
