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

$action = $data['action'];
$userId = $data['user_id'];
$matchId = $data['match_id'];

try {
    if ($action === 'signify') {
        // Validation for retroactive matches
        $stmtCheck = $pdo->prepare("SELECT is_retroactive, creator_area FROM match_schedules WHERE id = ?");
        $stmtCheck->execute([$matchId]);
        $matchData = $stmtCheck->fetch(PDO::FETCH_ASSOC);

        if ($matchData && !empty($matchData['is_retroactive'])) {
            $stmtUser = $pdo->prepare("SELECT area FROM users WHERE id = ?");
            $stmtUser->execute([$userId]);
            $userArea = $stmtUser->fetchColumn();

            if ($userArea !== $matchData['creator_area']) {
                echo json_encode(['status' => 'error', 'message' => 'This is a retroactive match and you do not belong to the allowed area.']);
                exit;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO match_significations (match_id, user_id, status) VALUES (?, ?, 'pending') ON DUPLICATE KEY UPDATE status = 'pending'");
        $stmt->execute([$matchId, $userId]);
        $sigId = $pdo->lastInsertId();
        if (!$sigId) {
            $stmtId = $pdo->prepare("SELECT id FROM match_significations WHERE match_id = ? AND user_id = ?");
            $stmtId->execute([$matchId, $userId]);
            $sigId = $stmtId->fetchColumn();
        }

        // Log
        $stmtMeta = $pdo->prepare("SELECT u.first_name, u.last_name, u.rank, u.role, m.match_name FROM users u, match_schedules m WHERE u.id = ? AND m.id = ?");
        $stmtMeta->execute([$userId, $matchId]);
        $meta = $stmtMeta->fetch(PDO::FETCH_ASSOC);
        $name = ($meta['first_name'] ?? '') . ' ' . ($meta['last_name'] ?? '');
        $rank = !empty($meta['rank']) ? $meta['rank'] : (!empty($meta['role']) ? $meta['role'] : 'Member');
        $description = "Signified by $name ($rank)";

        $stmtLog = $pdo->prepare("INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id) VALUES ('match_signification', ?, ?, 'pending', 'USER', ?)");
        $stmtLog->execute([$sigId, $description, $userId]);

        echo json_encode(['status' => 'success', 'message' => 'Signified successfully']);
    } elseif ($action === 'request_withdrawal') {
        $reason = isset($data['withdrawal_reason']) ? trim($data['withdrawal_reason']) : '';
        if ($reason === '') {
            echo json_encode(['status' => 'error', 'message' => 'Reason for withdrawal is required']);
            exit;
        }

        // Get signification and match start date
        $stmt = $pdo->prepare("
            SELECT ms.id, ms.status, m.start_date, m.match_name, u.first_name, u.last_name, u.rank, u.role
            FROM match_significations ms 
            JOIN match_schedules m ON m.id = ms.match_id 
            JOIN users u ON u.id = ms.user_id
            WHERE ms.match_id = ? AND ms.user_id = ?
        ");
        $stmt->execute([$matchId, $userId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            echo json_encode(['status' => 'error', 'message' => 'Signification record not found']);
            exit;
        }

        $currentStatus = $row['status'];
        if (!in_array($currentStatus, ['pending', 'approved', 'standby'])) {
            echo json_encode(['status' => 'error', 'message' => 'Current status does not allow withdrawal']);
            exit;
        }

        // Withdraw button active only 7 days before match
        $startDate = $row['start_date'];
        $today = date('Y-m-d');
        $cutoff = date('Y-m-d', strtotime($startDate . ' -7 days'));
        if ($today > $cutoff) {
            echo json_encode(['status' => 'error', 'message' => 'Withdrawal is only allowed until 7 days before the match start date.']);
            exit;
        }

        $stmt = $pdo->prepare("UPDATE match_significations SET status = 'withdrawal_requested', previous_status = ?, withdrawal_reason = ? WHERE match_id = ? AND user_id = ?");
        $stmt->execute([$currentStatus, $reason, $matchId, $userId]);

        // Log
        $name = ($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '');
        $rank = !empty($row['rank']) ? $row['rank'] : (!empty($row['role']) ? $row['role'] : 'Member');
        $description = "Withdrawal requested by $name ($rank)";
        $stmtLog = $pdo->prepare("INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id) VALUES ('match_signification', ?, ?, 'withdrawal_requested', 'USER', ?)");
        $stmtLog->execute([$row['id'], $description, $userId]);

        echo json_encode(['status' => 'success', 'message' => 'Withdrawal request submitted']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    }
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}
?>