<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminProductionActionsTenantController extends Controller
{
    private function guard(): array {
        require_admin_or_chair_tenant();
        require_org_context();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); exit; }
        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        return [$db,$orgId];
    }

    private function confOwnsSubmission(PDO $db, int $orgId, int $submissionId): array {
        $st=$db->prepare("
          SELECT s.id, s.conference_id
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          WHERE s.id=:id AND c.org_id=:o
          LIMIT 1
        ");
        $st->execute([':id'=>$submissionId,':o'=>$orgId]);
        $row=$st->fetch(PDO::FETCH_ASSOC);
        if(!$row){ http_response_code(404); echo "Not found"; exit; }
        return $row;
    }

    public function setStatus(): void
    {
        [$db,$orgId]=$this->guard();

        $submissionId=(int)($_POST['submission_id'] ?? 0);
        $status=trim((string)($_POST['status'] ?? ''));

        $row=$this->confOwnsSubmission($db,$orgId,$submissionId);

        // detect status column
        $st=$db->prepare("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='submissions' AND COLUMN_NAME IN ('workflow_status','status')");
        $st->execute();
        $col=$st->fetchColumn();
        if(!$col){ http_response_code(500); echo "No status column"; exit; }

        $db->prepare("UPDATE submissions SET `$col`=:s WHERE id=:id")->execute([':s'=>$status,':id'=>$submissionId]);

        if(function_exists('flash_set')) flash_set('success','Saved');
        header('Location: '.base_path('admin/production?conference_id='.(int)$row['conference_id'])); exit;
    }

    public function uploadGalley(): void
    {
        [$db,$orgId]=$this->guard();
        $submissionId=(int)($_POST['submission_id'] ?? 0);
        $row=$this->confOwnsSubmission($db,$orgId,$submissionId);

        // require submission_files table
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='submission_files'");
        $st->execute();
        if((int)$st->fetchColumn()<=0){ http_response_code(500); echo "submission_files missing"; exit; }

        if(empty($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])){
            if(function_exists('flash_set')) flash_set('danger','No file');
            header('Location: '.base_path('admin/galley?conference_id='.(int)$row['conference_id'])); exit;
        }

        $confId=(int)$row['conference_id'];
        $dir=BASE_PATH.'/public/assets/uploads/org_'.$orgId.'/galley/'.$confId.'/'.$submissionId;
        if(!is_dir($dir)) @mkdir($dir,0775,true);

        $ext=strtolower(pathinfo($_FILES['file']['name'] ?? '', PATHINFO_EXTENSION));
        if(!in_array($ext,['pdf','doc','docx','zip','png','jpg','jpeg','webp'],true)) $ext='bin';
        $fn='galley_'.date('Ymd_His').'_'.mt_rand(100,999).'.'.$ext;
        $dst=$dir.'/'.$fn;

        if(!@move_uploaded_file($_FILES['file']['tmp_name'],$dst)){
            if(function_exists('flash_set')) flash_set('danger','Upload failed');
            header('Location: '.base_path('admin/galley?conference_id='.(int)$row['conference_id'])); exit;
        }

        $path='assets/uploads/org_'.$orgId.'/galley/'.$confId.'/'.$submissionId.'/'.$fn;

        // insert file row (best-effort column detection)
        $st=$db->prepare("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='submission_files'");
        $st->execute();
        $cols=array_map(fn($r)=>$r['COLUMN_NAME'],$st->fetchAll(PDO::FETCH_ASSOC)?:[]);

        $map=['submission_id'=>$submissionId];
        if(in_array('file_path',$cols,true)) $map['file_path']=$path;
        elseif(in_array('path',$cols,true)) $map['path']=$path;

        if(in_array('file_type',$cols,true)) $map['file_type']='galley';
        elseif(in_array('category',$cols,true)) $map['category']='galley';

        if(in_array('original_name',$cols,true)) $map['original_name']=(string)($_FILES['file']['name'] ?? $fn);
        if(in_array('uploaded_by',$cols,true)) $map['uploaded_by']=(int)(function_exists('auth_id')?auth_id():0);
        if(in_array('created_at',$cols,true)) {} // auto

        $fields=array_keys($map);
        $placeholders=array_map(fn($f)=>':'.$f,$fields);
        $sql="INSERT INTO submission_files (".implode(',',$fields).") VALUES (".implode(',',$placeholders).")";
        $st=$db->prepare($sql);
        $bind=[];
        foreach($map as $k=>$v){ $bind[':'.$k]=$v; }
        $st->execute($bind);

        if(function_exists('flash_set')) flash_set('success','Uploaded');
        header('Location: '.base_path('admin/galley?conference_id='.(int)$row['conference_id'])); exit;
    }

    public function publishProceedings(): void
    {
        [$db,$orgId]=$this->guard();
        $confId=(int)($_POST['conference_id'] ?? 0);

        // validate conference in org
        $st=$db->prepare("SELECT id FROM conferences WHERE id=:id AND org_id=:o LIMIT 1");
        $st->execute([':id'=>$confId,':o'=>$orgId]);
        if(!(int)$st->fetchColumn()){ http_response_code(404); echo "Conference not found"; exit; }

        // set conference status to published (if exists)
        $db->prepare("UPDATE conferences SET status='published' WHERE id=:id")->execute([':id'=>$confId]);

        if(function_exists('flash_set')) flash_set('success','Published');
        header('Location: '.base_path('admin/proceedings?conference_id='.$confId)); exit;
    }
}
