<?php
// ajax/update_submission_status.php
error_reporting(0);
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/reviewer_sync.php';
startSession();
header('Content-Type: application/json');

$user    = getCurrentUser();
$user_id = $user['user_id'];
$sid     = (int)($_POST['submission_id'] ?? 0);
$status  = trim($_POST['status'] ?? '');

$valid = ['draft','submitted','under_review','accepted','rejected'];
if (!$sid || !in_array($status, $valid)) {
    echo json_encode(['success'=>false,'message'=>'Invalid request']); exit;
}

// ── Generate unique tracking code ─────────────────────────
function generateTrackingCode(PDO $db): string {
    $attempts = 0;
    do {
        $letters = strtoupper(chr(rand(65,90)).chr(rand(65,90)));
        $digits  = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $code    = 'CIJSS-' . $letters . $digits;
        $q = $db->prepare("SELECT 1 FROM submissions WHERE tracking_code=? LIMIT 1");
        $q->execute([$code]);
        $exists = $q->fetchColumn();
        $attempts++;
    } while ($exists && $attempts < 100);
    return $code;
}

try {
    // Ensure columns exist
    try {
        db()->exec("ALTER TABLE submissions
            ADD COLUMN IF NOT EXISTS submission_status
                ENUM('draft','submitted','under_review','accepted','rejected')
                NOT NULL DEFAULT 'draft',
            ADD COLUMN IF NOT EXISTS tracking_code VARCHAR(20) NULL UNIQUE,
            ADD COLUMN IF NOT EXISTS submitted_at  DATETIME NULL");
    } catch(PDOException $e) {}

    // Check ownership + get current status
    $q = db()->prepare(
        "SELECT submission_status, tracking_code FROM submissions WHERE submission_id=? AND user_id=?"
    );
    $q->execute([$sid, $user_id]);
    $row = $q->fetch();

    if (!$row) {
        echo json_encode(['success'=>false,'message'=>'Submission not found']); exit;
    }

    $current      = $row['submission_status'] ?? 'draft';
    $existingCode = $row['tracking_code'];

    // Users can only: draft→submitted
    if ($status === 'submitted' && $current !== 'draft') {
        echo json_encode(['success'=>false,'message'=>"Already $current"]); exit;
    }

    $trackingCode = $existingCode;
    $submittedAt  = null;

    if ($status === 'submitted') {
        // Generate tracking code if not already set
        if (empty($existingCode)) {
            $trackingCode = generateTrackingCode(db());
        }
        $submittedAt = date('Y-m-d H:i:s');

        db()->prepare(
            "UPDATE submissions
             SET submission_status=?,
                 tracking_code=?,
                 submitted_at=?,
                 updated_at=NOW()
             WHERE submission_id=? AND user_id=?"
        )->execute([$status, $trackingCode, $submittedAt, $sid, $user_id]);

    } else {
        db()->prepare(
            "UPDATE submissions SET submission_status=?, updated_at=NOW()
             WHERE submission_id=? AND user_id=?"
        )->execute([$status, $sid, $user_id]);
    }

    // ── Sync suggested reviewers to users table ───────────
    $syncResult = ['synced'=>0,'skipped'=>0,'errors'=>[]];
    if ($status === 'submitted') {
        try {
            $syncResult = syncSubmissionReviewers(db(), $sid);
        } catch(Exception $e) {
            error_log('Reviewer sync error: ' . $e->getMessage());
        }
    }

    echo json_encode([
        'success'          => true,
        'status'           => $status,
        'tracking_code'    => $trackingCode ?? null,
        'submitted_at'     => $submittedAt  ?? null,
        'reviewers_synced' => $syncResult['synced'],
    ]);

} catch(PDOException $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}