<?php
declare(strict_types=1);
if (session_status()===PHP_SESSION_NONE) session_start();
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/helpers.php';

require_role(['super_admin','admin','branch_admin']);
header('Content-Type: application/json');

$action=trim((string)($_POST['action']??'')); $sid=(int)($_POST['submission_id']??0);
$uid=(int)($_SESSION['user']['id'] ?? 0);
if(!$sid || $action===''){ echo json_encode(['ok'=>false,'error'=>'missing']); exit; }

try{
  if($action==='approve'){
    $finalScore = ($_POST['final_score']!=='') ? (float)$_POST['final_score'] : null;
    $st=$mysqli->prepare("UPDATE lms_submissions
                          SET admin_reviewer_id=?, admin_approved_at=NOW(),
                              workflow_status='approved',
                              final_score=IFNULL(?,final_score),
                              updated_at=NOW()
                          WHERE id=?");
    $st->bind_param('idi',$uid,$finalScore,$sid); $st->execute();
    echo json_encode(['ok'=>true]); exit;
  }
  if($action==='release'){
    $st=$mysqli->prepare("UPDATE lms_submissions
                          SET admin_reviewer_id=?, admin_approved_at=IFNULL(admin_approved_at,NOW()),
                              workflow_status='released',
                              release_mode='immediate',
                              release_at=NOW(), updated_at=NOW()
                          WHERE id=?");
    $st->bind_param('ii',$uid,$sid); $st->execute();
    echo json_encode(['ok'=>true]); exit;
  }
  if($action==='schedule'){
    $releaseAt = trim((string)($_POST['release_at']??''));
    $st=$mysqli->prepare("UPDATE lms_submissions
                          SET admin_reviewer_id=?, admin_approved_at=IFNULL(admin_approved_at,NOW()),
                              workflow_status='approved',
                              release_mode='on_date',
                              release_at=?, updated_at=NOW()
                          WHERE id=?");
    $st->bind_param('isi',$uid,$releaseAt,$sid); $st->execute();
    echo json_encode(['ok'=>true]); exit;
  }
  if($action==='return'){
    $reason=trim((string)($_POST['reason']??''));
    $st=$mysqli->prepare("UPDATE lms_submissions
                          SET admin_reviewer_id=?, workflow_status='needs_correction',
                              needs_correction_reason=?, updated_at=NOW()
                          WHERE id=?");
    $st->bind_param('isi',$uid,$reason,$sid); $st->execute();
    echo json_encode(['ok'=>true]); exit;
  }
  echo json_encode(['ok'=>false,'error'=>'unknown action']);
}catch(Throwable $e){
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>'server','detail'=>$e->getMessage()]);
}
