<?php
require_once '../config/cors.php';
header('Content-Type: application/json');

require_once '../config/db.php';

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['match_id']) || !isset($data['user_id']) || !isset($data['states_number']) || !isset($data['rm_signature'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

$matchId = (int) $data['match_id'];
$userId = (int) $data['user_id'];
$statesNumber = trim($data['states_number'] ?? '');
$signatureData = $data['rm_signature'] ?? '';

if ($statesNumber === '') {
    echo json_encode(['status' => 'error', 'message' => 'Stage number is required']);
    exit;
}

$lroName = trim($data['lro_name'] ?? '');
if ($lroName === '') {
    echo json_encode(['status' => 'error', 'message' => 'LRO name is required']);
    exit;
}

// Check match exists
$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;
}

$createTableSql = "
    CREATE TABLE IF NOT EXISTS `match_states_assignments` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `match_id` INT NOT NULL,
        `states_number` VARCHAR(100) NOT NULL,
        `lro_name` VARCHAR(255) 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_states` (`match_id`, `submitted_by`)
    )
";
try {
    $pdo->exec($createTableSql);
} catch (Exception $createEx) {
    // Ignore so we don't break if table exists or permission denied
}
// Add lro_name and role columns if table already existed without them
try {
    $pdo->exec("ALTER TABLE match_states_assignments ADD COLUMN lro_name VARCHAR(255) NULL AFTER states_number");
} catch (Exception $alterEx) {
}
try {
    $pdo->exec("ALTER TABLE match_states_assignments ADD COLUMN role VARCHAR(100) NULL AFTER lro_name");
} catch (Exception $alterEx) {
}

try {
    $signaturePath = '';
    if (!empty($signatureData)) {
        if (preg_match('/^data:image\/(\w+);base64,/', $signatureData, $type)) {
            $signatureData = substr($signatureData, strpos($signatureData, ',') + 1);
            $type = strtolower($type[1]);
        } else {
            $type = 'png';
        }
        $signatureData = base64_decode($signatureData);
        if ($signatureData === false) {
            throw new Exception('Base64 decode failed');
        }
        $filename = 'states_sig_' . $matchId . '_' . time() . '.' . $type;
        $uploadDir = '../storage/assignments_signatures/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $filePath = $uploadDir . $filename;
        if (file_put_contents($filePath, $signatureData)) {
            $signaturePath = 'storage/assignments_signatures/' . $filename;
        } else {
            throw new Exception('Failed to save signature file');
        }
    }

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

    $stmt = $pdo->prepare("
        INSERT INTO match_states_assignments (match_id, states_number, lro_name, role, rm_signature, submitted_by)
        VALUES (?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE states_number = VALUES(states_number), lro_name = VALUES(lro_name), role = VALUES(role), rm_signature = VALUES(rm_signature)
    ");
    $stmt->execute([$matchId, $statesNumber, $lroName, $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]);
    }

    echo json_encode([
        'status' => 'success',
        'message' => 'Stage assignment saved successfully',
    ]);
} catch (PDOException $e) {
    $isTableMissing = ($e->getCode() === '42S02' || (int) $e->getCode() === 1146 || stripos($e->getMessage(), "doesn't exist") !== false);
    if ($isTableMissing) {
        try {
            $pdo->exec($createTableSql);
            $stmt = $pdo->prepare("
                INSERT INTO match_states_assignments (match_id, states_number, lro_name, role, rm_signature, submitted_by)
                VALUES (?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE states_number = VALUES(states_number), lro_name = VALUES(lro_name), role = VALUES(role), rm_signature = VALUES(rm_signature)
            ");
            $stmt->execute([$matchId, $statesNumber, $lroName, $role, $signaturePath, $userId]);
            echo json_encode([
                'status' => 'success',
                'message' => 'Stage assignment saved successfully',
            ]);
        } catch (Exception $retryEx) {
            echo json_encode([
                'status' => 'error',
                'message' => 'Error: ' . $retryEx->getMessage(),
            ]);
        }
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Error: ' . $e->getMessage(),
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage(),
    ]);
}
