<?php
if(isset($message) && isset($message->left_chat_member)) {
    $leftUserId = $message->left_chat_member->id ?? null;

if($leftUserId) {
        $channelUsername = $message->chat->username ?? null;
        $channelTitle    = $message->chat->title ?? null;
        $stmt = $pdo->prepare("SELECT * FROM `memberships` WHERE `user_id` = ? AND `status` = 'active' AND ((`channel_username` = ?) OR (`channel_name` = ?)) ORDER BY `joined_at` DESC LIMIT 1");
        $stmt->execute([$leftUserId, $channelUsername, $channelTitle]);
        $m = $stmt->fetch();

if($m) {
            try {
                $pdo->beginTransaction();
                $stmtOrder = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? FOR UPDATE");
                $stmtOrder->execute([$m->order_id]);
                $order = $stmtOrder->fetch();

if(!$order) {
                    $pdo->rollBack();
} else {
                    $joinTime     = strtotime($m->joined_at);
                    $timeDiff     = time() - $joinTime;
                    $requiredTime = 604800;

if($timeDiff < $requiredTime) {
                        $leaver      = getUser($leftUserId);
                        $isLeaverVip = $leaver->is_vip && strtotime($leaver->vip_expire) > time();
                        $baseCost    = $order->coin_per_member;

if($isLeaverVip) {
                            $penaltyAmount = 2.5;
} else {
                            $penaltyAmount = 5;
}

                        $stmtDed = $pdo->prepare("UPDATE `users` SET `coins` = `coins` - ? WHERE `user_id` = ?");
                        $stmtDed->execute([$penaltyAmount, $leftUserId]);
                        $responseText = "*اخطار خروج از کانال ⚠️*
🔰با توجه به خروج زودهنگام از کانال *$channelTitle* از شما *$penaltyAmount سکه* جریمه کسر گردید.
*📣 حداقل باید ۷ روز در کانال های عضو شده باقی بمانید.*";
                        sendMessage($leftUserId, $responseText);
                        $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_refunded', `left_at` = NOW(), `penalty_applied` = 1 WHERE `id` = ?");
                        $stmtUpd->execute([$m->id]);
                        $stmtDec = $pdo->prepare("UPDATE `orders` SET `members_done` = IF(`members_done` > 0, `members_done` - 1, 0) WHERE `order_id` = ?");
                        $stmtDec->execute([$m->order_id]);
} else {
                        $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_expired', `left_at` = NOW() WHERE `id` = ?");
                        $stmtUpd->execute([$m->id]);
}

                    $pdo->commit();
}

} catch (Exception $e) {

if($pdo->inTransaction()) {
                    $pdo->rollBack();
}

}

}

}

    die;
}


if(isset($update) && isset($update->chat_member)) {
    $cm         = $update->chat_member;
    $newStatus  = $cm->new_chat_member->status ?? null;
    $oldStatus  = $cm->old_chat_member->status ?? null;
    $leftUserId = $cm->new_chat_member->user->id ?? null;

if($leftUserId && in_array($newStatus, ['left', 'kicked'], true) && in_array($oldStatus, ['member', 'administrator', 'creator'], true)) {
        $channelUsername = $cm->chat->username ?? null;
        $channelTitle    = $cm->chat->title ?? null;
        $stmt = $pdo->prepare("SELECT * FROM `memberships` WHERE `user_id` = ? AND `status` = 'active' AND ((`channel_username` = ?) OR (`channel_name` = ?)) ORDER BY `joined_at` DESC LIMIT 1");
        $stmt->execute([$leftUserId, $channelUsername, $channelTitle]);
        $m = $stmt->fetch();

if($m) {
            try {
                $pdo->beginTransaction();
                $stmtOrder = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? FOR UPDATE");
                $stmtOrder->execute([$m->order_id]);
                $order = $stmtOrder->fetch();

if(!$order) {
                    $pdo->rollBack();
} else {
                    $joinTime     = strtotime($m->joined_at);
                    $timeDiff     = time() - $joinTime;
                    $requiredTime = 604800;

if($timeDiff < $requiredTime) {
                        $leaver      = getUser($leftUserId);
                        $isLeaverVip = $leaver->is_vip && strtotime($leaver->vip_expire) > time();
                        $baseCost    = $order->coin_per_member;

if($isLeaverVip) {
                            $penaltyAmount = 2.5;
} else {
                            $penaltyAmount = 5;
}

                        $stmtDed = $pdo->prepare("UPDATE `users` SET `coins` = `coins` - ? WHERE `user_id` = ?");
                        $stmtDed->execute([$penaltyAmount, $leftUserId]);
                        $responseText = "*اخطار خروج از کانال ⚠️*
🔰با توجه به خروج زودهنگام از کانال *$channelTitle* از شما *$penaltyAmount سکه* جریمه کسر گردید.
*📣 حداقل باید ۷ روز در کانال های عضو شده باقی بمانید.*";
                        sendMessage($leftUserId, $responseText);
                        $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_refunded', `left_at` = NOW(), `penalty_applied` = 1 WHERE `id` = ?");
                        $stmtUpd->execute([$m->id]);
                        $stmtDec = $pdo->prepare("UPDATE `orders` SET `members_done` = IF(`members_done` > 0, `members_done` - 1, 0) WHERE `order_id` = ?");
                        $stmtDec->execute([$m->order_id]);
} else {
                        $stmtUpd = $pdo->prepare("UPDATE `memberships` SET `status` = 'left_expired', `left_at` = NOW() WHERE `id` = ?");
                        $stmtUpd->execute([$m->id]);
}

                    $pdo->commit();
}

} catch (Exception $e) {

if($pdo->inTransaction()) {
                    $pdo->rollBack();
}

}

}

        die;
}

}