<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AuthorDashboardStableController extends Controller
{
    private function hasCol($db, string $table, string $col): bool {
        $st = $db->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $st->execute([':t'=>$table, ':c'=>$col]);
        return (int)$st->fetchColumn() > 0;
    }

    public function index(): void
    {
        require_author_area();

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

        $titleEn = $this->hasCol($db,'submissions','title_en') ? 'title_en' : ($this->hasCol($db,'submissions','title') ? 'title' : null);
        $titleAr = $this->hasCol($db,'submissions','title_ar') ? 'title_ar' : null;
        $stCol   = $this->hasCol($db,'submissions','status') ? 'status' : null;
        $created = $this->hasCol($db,'submissions','created_at') ? 'created_at' : 'id';

        // author_id column name varies in packs
        $authorCol = null;
        foreach (['author_id','user_id','created_by'] as $c) {
            if ($this->hasCol($db,'submissions',$c)) { $authorCol = $c; break; }
        }

        $rows = [];
        if ($authorCol) {
            $st = $db->prepare("SELECT * FROM submissions WHERE $authorCol = :u ORDER BY $created DESC LIMIT 200");
            $st->execute([':u'=>$uid]);
            $rows = $st->fetchAll() ?: [];
        }

        $this->view('author/stable/index', [
            'rows'=>$rows,
            'titleEn'=>$titleEn,
            'titleAr'=>$titleAr,
            'stCol'=>$stCol,
            'authorCol'=>$authorCol,
        ]);
    }
}
