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

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

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

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

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

// Auto-calculate points from match level and disciplines (Level × disciplines)
$stmtMatch = $pdo->prepare("SELECT match_level, range_master FROM match_schedules WHERE id = ?");
$stmtMatch->execute([$matchId]);
$match = $stmtMatch->fetch(PDO::FETCH_ASSOC);
if (!$match) {
    echo json_encode(['status' => 'error', 'message' => 'Match not found']);
    exit;
}
$points = nroi_compute_match_points($match['match_level'], $match['range_master']);

try {
    // Process Signature: Save as File
    $signaturePath = '';
    if (!empty($signatureData)) {
        // Remove header if present (e.g., data:image/png;base64,)
        if (preg_match('/^data:image\/(\w+);base64,/', $signatureData, $type)) {
            $signatureData = substr($signatureData, strpos($signatureData, ',') + 1);
            $type = strtolower($type[1]); // png, jpg, etc
        } else {
            $type = 'png';
        }

        $signatureData = base64_decode($signatureData);
        if ($signatureData === false) {
            throw new Exception('Base64 decode failed');
        }

        $filename = 'sig_' . $matchId . '_' . $userId . '_' . time() . '.' . $type;
        $uploadDir = '../storage/rm_signatures/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $filePath = $uploadDir . $filename;
        if (file_put_contents($filePath, $signatureData)) {
            $signaturePath = 'storage/rm_signatures/' . $filename;
        } else {
            throw new Exception('Failed to save signature file');
        }
    }

    // Handle Assignment Updates from RM if provided
    $updateType = $data['assignment_type'] ?? '';
    $updateRole = $data['role'] ?? '';
    $updateOfficer = $data['officer_name'] ?? '';
    $updateStageNum = $data['stage_number'] ?? '';

    if ($updateType !== '' && $updateRole !== '') {
        // Create table if not exists and update assignment info
        if ($updateType === 'states') {
            $atbl = 'match_states_assignments';
            $pdo->exec("CREATE TABLE IF NOT EXISTS `$atbl` (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 uniq_ms (match_id, submitted_by))");
            $stmtA = $pdo->prepare("INSERT INTO `$atbl` (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)");
            $stmtA->execute([$matchId, $updateStageNum, $updateOfficer, $updateRole, $signaturePath, $userId]);
        } else {
            $atbl = 'match_' . $updateType . '_assignments';
            $pdo->exec("CREATE TABLE IF NOT EXISTS `$atbl` (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 uniq_{$updateType} (match_id, submitted_by))");
            try {
                $pdo->exec("ALTER TABLE `$atbl` ADD COLUMN role VARCHAR(100) NULL AFTER officer_name");
            } catch (Exception $e) {
            }
            try {
                $pdo->exec("ALTER TABLE `$atbl` ADD COLUMN rm_signature VARCHAR(255) NULL AFTER role");
            } catch (Exception $e) {
            }

            $stmtA = $pdo->prepare("INSERT INTO `$atbl` (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)");
            $stmtA->execute([$matchId, $updateOfficer, $updateRole, $signaturePath, $userId]);
        }

        // Sync Profile
        $profileTypeName = ($updateType === 'states') ? 'Stage' : $updateType;
        if ($updateType !== 'states') {
            // Try to find full name from references
            $stmtRef = $pdo->query("SELECT name FROM reference_match_assignments");
            while ($row = $stmtRef->fetchColumn()) {
                $rKey = strtolower(str_replace(' ', '_', $row));
                if ($rKey === $updateType) {
                    $profileTypeName = $row;
                    break;
                }
            }
        }
        $pdo->prepare("UPDATE users SET match_assignment = ?, match_role = ? WHERE id = ?")
            ->execute([$profileTypeName, $updateRole, $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]);
    }

    // Insert/update match_points (without user_role for compatibility with DBs that don't have that column yet)
    $stmt = $pdo->prepare("INSERT INTO match_points (match_id, user_id, points, rm_signature) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE points = ?, rm_signature = ?");
    $stmt->execute([$matchId, $userId, $points, $signaturePath, $points, $signaturePath]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Match points saved successfully',
        'file' => $signaturePath,
        'points' => (int) $points
    ]);
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>