<?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['participant_id']) || !isset($data['rm_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

$matchId = (int) $data['match_id'];
$participantId = (int) $data['participant_id'];
$rmId = (int) $data['rm_id'];

try {
    // 1. Fetch RM's signature
    // From conversation log: officer signatures are stored in storage/officers_signature/ 
    // and prefixed with officer_{id}_
    $sigDir = '../storage/officers_signature/';
    $files = glob($sigDir . 'officer_' . $rmId . '_*');

    if (empty($files)) {
        echo json_encode(['status' => 'error', 'message' => 'Your signature matches not found. Please set it in your profile first.']);
        exit;
    }

    // Sort by time to get latest
    usort($files, function ($a, $b) {
        return filemtime($b) - filemtime($a);
    });

    $rmSignaturePath = str_replace('../', '', $files[0]);

    // 2. Fetch match details for point calculation
    $stmtMatch = $pdo->prepare("SELECT match_level, range_master FROM match_schedules WHERE id = ?");
    $stmtMatch->execute([$matchId]);
    $match = $stmtMatch->fetch(PDO::FETCH_ASSOC);
    if (!$match) {
        throw new Exception('Match not found');
    }
    $points = nroi_compute_match_points($match['match_level'], $match['range_master']);

    // 3. Update or Insert match_points for the participant
    $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, $participantId, $points, $rmSignaturePath, $points, $rmSignaturePath]);

    // Reset is_extended/is_rm_enabled for the participant if RM is signing
    $pdo->prepare("UPDATE match_significations SET is_extended = 0, is_rm_enabled = 0 WHERE match_id = ? AND user_id = ?")->execute([$matchId, $participantId]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Participant signed successfully',
        'points' => $points,
        'signature' => $rmSignaturePath
    ]);

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>