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

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

function getUserTotalPoints($pdo, $userId)
{
    $stmt = $pdo->prepare("
        SELECT 
            (SELECT COALESCE(SUM(mp.points), 0) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id = ?) + 
            (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = ?) as total_points
    ");
    $stmt->execute([$userId, $userId]);
    return (float) $stmt->fetchColumn();
}

try {
    $sigId = $data['signification_id'] ?? null;
    $status = $data['status'] ?? null;
    $rmId = $data['rm_id'] ?? null;
    $deductionPoints = isset($data['deduction_points']) ? (float) $data['deduction_points'] : 0;
    $remarks = $data['remarks'] ?? '';

    if (!$sigId || !$status || !$rmId) {
        throw new Exception('Missing required fields');
    }

    if (!in_array($status, ['approved', 'standby', 'declined', 'withdrawn', 'withdrawal_requested', 'reject_withdrawal'])) {
        throw new Exception('Invalid status');
    }

    // Verify RM assignment and get user info
    $stmt = $pdo->prepare("
        SELECT m.rm_id, m.match_name, m.start_date, m.end_date, m.location,
               ms.match_id, ms.user_id, ms.withdrawal_reason, ms.previous_status,
               u.email, u.first_name, u.last_name, u.nroi_id,
               (SELECT 1 FROM match_points mp WHERE mp.match_id = ms.match_id AND mp.user_id = ms.user_id AND mp.rm_signature IS NOT NULL AND mp.rm_signature != '') as is_served
        FROM match_significations ms
        JOIN match_schedules m ON ms.match_id = m.id
        JOIN users u ON ms.user_id = u.id
        WHERE ms.id = ?
    ");
    $stmt->execute([$sigId]);
    $info = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$info || $info['rm_id'] != $rmId) {
        throw new Exception('Unauthorized: Not the assigned RM for this match');
    }

    if ($status === 'withdrawn' && !empty($info['is_served'])) {
        throw new Exception('Cannot withdraw a member who has already served the match.');
    }

    // Update status
    $pdo->beginTransaction();
    
    $finalStatus = $status;
    $notifStatus = $status;
    $prevStatusVal = $info['previous_status'] ?? 'approved';
    
    if ($status === 'reject_withdrawal') {
        $finalStatus = $prevStatusVal;
        $notifStatus = 'Withdrawal Rejected';
    }

    $stmt = $pdo->prepare("UPDATE match_significations SET status = ?, officer_remarks = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id = ?");
    $stmt->execute([$finalStatus, $remarks, $rmId, $sigId]);

    // Handle point deduction (demerit)
    if ($status === 'withdrawn' && $deductionPoints > 0) {
        $negativePoints = -$deductionPoints;
        $stmtPts = $pdo->prepare("INSERT INTO match_points (match_id, user_id, points, rm_signature) VALUES (?, ?, ?, 'DEMERIT') ON DUPLICATE KEY UPDATE points = points + ?");
        $stmtPts->execute([$info['match_id'], $info['user_id'], $negativePoints, $negativePoints]);
    }
    $pdo->commit();

    // Log activity
    $stmtRM = $pdo->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
    $stmtRM->execute([$rmId]);
    $rm = $stmtRM->fetch(PDO::FETCH_ASSOC);
    $rmName = trim(($rm['first_name'] ?? '') . ' ' . ($rm['last_name'] ?? ''));

    $description = ucfirst($status) . " by RM $rmName for: " . ($info['first_name'] ?? '') . " " . ($info['last_name'] ?? '') . " (NROI ID: " . ($info['nroi_id'] ?? 'N/A') . ") - Match: " . ($info['match_name'] ?? 'N/A');

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

    // Send Email Notification
    if (!empty($info['email'])) {
        $fullName = trim(($info['first_name'] ?? '') . ' ' . ($info['last_name'] ?? ''));
        $sDate = strtotime($info['start_date']);
        $eDate = strtotime($info['end_date']);
        $schedule = (date('Y-m-d', $sDate) === date('Y-m-d', $eDate))
            ? date('M d, Y', $sDate)
            : date('M d', $sDate) . ' - ' . date('M d, Y', $eDate);

        // Reason logic: Use RM remarks if provided (for rejection or direct withdrawal). 
        // Fallback to user's withdrawal reason only if RM remarks are empty and it's a withdrawal.
        $reason = !empty($remarks) ? $remarks : (($status === 'withdrawn') ? ($info['withdrawal_reason'] ?? 'Directly withdrawn by Range Master') : '');

        // Calculate remaining points
        $remainingPoints = getUserTotalPoints($pdo, $info['user_id']);

        // Notification status label
        $statusLabel = ($notifStatus === 'declined') ? 'Declined' : (($notifStatus === 'withdrawn') ? 'Withdrawn' : (($notifStatus === 'Withdrawal Rejected') ? 'Withdrawal Rejected' : ucfirst($notifStatus)));

        sendMatchNotification($info['email'], $fullName, $statusLabel, $info['match_name'], $schedule, $info['location'], $reason, 'RM', $deductionPoints, $remainingPoints, $prevStatusVal);
    }

    echo json_encode(['status' => 'success', 'message' => 'Status updated successfully']);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>