<?php
/**
 * Save assignment for a match: Chrono, Stats, or Equipment check.
 * Same flow as Stage: officer name + RM signature, one record per match.
 * POST: type (chrono|stats|equipment_check), match_id, user_id, officer_name, rm_signature (base64)
 */
require_once __DIR__ . '/../config/cors.php';
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

$data = json_decode(file_get_contents('php://input'), true) ?: [];

$type = strtolower(trim($data['type'] ?? ''));

// Fetch allowed types from reference_match_assignments
$stmtRef = $pdo->query("SELECT name FROM reference_match_assignments");
$allowed = ['chrono', 'stats', 'equipment_check', 'quarter_master', 'range_master'];
while ($row = $stmtRef->fetchColumn()) {
    $allowed[] = strtolower(str_replace(' ', '_', trim($row)));
}

if (!in_array($type, $allowed, true)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid type.']);
    exit;
}

$matchId = (int) ($data['match_id'] ?? 0);
$userId = (int) ($data['user_id'] ?? 0);
$officerName = trim($data['officer_name'] ?? '');
$signatureData = $data['rm_signature'] ?? '';

if ($matchId < 1 || $userId < 1) {
    echo json_encode(['status' => 'error', 'message' => 'match_id and user_id are required']);
    exit;
}
if ($officerName === '') {
    $label = ucfirst(str_replace('_', ' ', $type));
    echo json_encode(['status' => 'error', 'message' => $label . ' officer name is required']);
    exit;
}

$stmtMatch = $pdo->prepare("SELECT id FROM match_schedules WHERE id = ?");
$stmtMatch->execute([$matchId]);
if (!$stmtMatch->fetch()) {
    echo json_encode(['status' => 'error', 'message' => 'Match not found']);
    exit;
}

$table = 'match_' . $type . '_assignments';
$createSql = "
    CREATE TABLE IF NOT EXISTS `$table` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `match_id` INT NOT NULL,
        `officer_name` VARCHAR(255) NOT NULL,
        `role` VARCHAR(100) NULL,
        `rm_signature` VARCHAR(255) NULL,
        `submitted_by` INT NOT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY `unique_match_user_$type` (`match_id`, `submitted_by`)
    )
";
try {
    $pdo->exec($createSql);
} catch (Exception $e) {
}

try {
    $pdo->exec("ALTER TABLE `$table` ADD COLUMN role VARCHAR(100) NULL AFTER officer_name");
} catch (Exception $e) {
}

$signaturePath = '';
if (!empty($signatureData)) {
    if (preg_match('/^data:image\/(\w+);base64,/', $signatureData, $m)) {
        $signatureData = substr($signatureData, strpos($signatureData, ',') + 1);
        $ext = strtolower($m[1]);
    } else {
        $ext = 'png';
    }
    $raw = base64_decode($signatureData, true);
    if ($raw === false) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid signature image']);
        exit;
    }
    $dir = __DIR__ . '/../storage/assignments_signatures/';
    if (!is_dir($dir))
        mkdir($dir, 0777, true);
    $file = $type . '_sig_' . $matchId . '_' . time() . '.' . $ext;
    if (file_put_contents($dir . $file, $raw)) {
        $signaturePath = 'storage/assignments_signatures/' . $file;
    }
}

try {
    $role = trim($data['role'] ?? '');

    $stmt = $pdo->prepare("
        INSERT INTO `$table` (match_id, officer_name, role, rm_signature, submitted_by)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE officer_name = VALUES(officer_name), role = VALUES(role), rm_signature = VALUES(rm_signature)
    ");
    $stmt->execute([$matchId, $officerName, $role, $signaturePath, $userId]);

    // Reset is_extended/is_rm_enabled if RM is signing
    if ($signaturePath !== '') {
        $pdo->prepare("UPDATE match_significations SET is_extended = 0, is_rm_enabled = 0 WHERE match_id = ? AND user_id = ?")->execute([$matchId, $userId]);
    }
    $label = ucfirst(str_replace('_', ' ', $type));
    echo json_encode([
        'status' => 'success',
        'message' => $label . ' assignment saved successfully',
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage(),
    ]);
}
